幾種java網絡編程客戶端的代碼

順序跟服務端的對應,說白了這個比服務器端簡單一些,就分是io弄出來的仍是nio弄出來的,而後就是一些細節了好比socket,InetAddress之類的,仍是得多敲,敲多了就熟了。 java


1 import java.io.*;
import java.util.*;
import java.net.*;
public class EchoClient{
 private String host ="localhost";
 private int port = 8000;
 private Socket socket;
 public EchoClient() throws IOException{
  socket =new Socket(host,port);
  
 }
 public static void main(String[] args) throws IOException{
  new EchoClient().talk();
 }
 private PrintWriter getWriter(Socket socket)throws IOException{
  OutputStream socketOut = socket.getOutputStream();
  return new PrintWriter(socketOut,true);
  
 }
 private BufferedReader getReader(Socket socket)throws IOException{
  InputStream socketIn = socket.getInputStream();
  return new BufferedReader(new InputStreamReader(socketIn));
 }
 public void talk() throws IOException{
  try{
   BufferedReader br = getReader(socket);
   PrintWriter pw = getWriter(socket);
   BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
   String msg = null;
   while((msg = localReader.readLine())!= null){
    pw.println(msg);
    System.out.println(br.readLine());
    if(msg.equals("bye"))
     break;
   }
  }catch(IOException e){
   e.printStackTrace();
  }finally{
   try{
    if(socket != null)
     socket.close();
   }catch(IOException e){
    e.printStackTrace();
   }
  }
 }
} 服務器

2這個是用nio寫的 socket

import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.io.*;
import java.nio.charset.*; .net

public class EchoClient2{
 private SocketChannel socketChannel = null;
 public EchoClient2()throws IOException{
  socketChannel = SocketChannel.open();
  InetAddress ia = InetAddress.getLocalHost();
  InetSocketAddress isa = new InetSocketAddress(ia,8000);
  socketChannel.connect(isa);//鏈接服務器
  System.out.println("與服務器的鏈接創建成功");
  
  
 }
 private PrintWriter getWriter(Socket socket)throws IOException{
  OutputStream socketOut = socket.getOutputStream();
  return new PrintWriter(socketOut,true);
 }
 private BufferedReader getReader(Socket socket)throws IOException{
  InputStream socketIn = socket.getInputStream();
  return new BufferedReader(new InputStreamReader(socketIn));
 }
 public void talk()throws IOException{
  try{
   BufferedReader br = getReader(socketChannel.socket());
   PrintWriter pw = getWriter(socketChannel.socket());
   BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
   String msg = null;
   while((msg = localReader.readLine())!= null){
    pw.println(msg);
    System.out.println(br.readLine());
    if(msg.equals("bye"))
     break;
   }
  }catch(IOException e)
  {
   e.printStackTrace();
  }finally{
   try{
    socketChannel.close();
   }catch(IOException e){
    e.printStackTrace();
   }
  }
 }
 public static void main(String args[])throws IOException{
  new EchoClient2().talk();
 }
} get

相關文章
相關標籤/搜索