java网络编程:socket与sockeserver

开始研究java的网络编程,建议先从socket开始吧。下面是一个简单的client/server的例子:

客户端代码:

Java代码  收藏代码
  1. public class TCPECHOClient {
  2.     public static void main(String[] args) {
  3.         String server = “localhost”;
  4.         String data = “Echo this!”;
  5.         byte[] bs = data.getBytes();
  6.         try {
  7.             Socket socket = new Socket(server,80);
  8.             System.out.println(“Connecting to server……”);
  9.             InputStream in = socket.getInputStream();
  10.             OutputStream out = socket.getOutputStream();
  11.             out.write(bs);
  12.             int totalDateRecived = 0;
  13.             int bytesRecvd = 0 ;
  14.             while(totalDateRecived<bs.length){
  15.                 totalDateRecived +=bytesRecvd;
  16.                 if((bytesRecvd=in.read(bs,totalDateRecived,bs.length-totalDateRecived))==-1)
  17.                 throw new SocketException(“connection closed!”);
  18.             }
  19.             System.out.println(“received:”+new String(bs));
  20.             socket.close();
  21.         } catch (UnknownHostException e) {
  22.             e.printStackTrace();
  23.         } catch (IOException e) {
  24.             e.printStackTrace();
  25.         }
  26.     }
  27. }

服务端:

Java代码  收藏代码
  1. public class TCPEchoServer {
  2.     private static int BUFSiZE = 32;
  3.     public static void main(String[] args) {
  4.         try {
  5.             ServerSocket serverSocket = new ServerSocket(80);
  6.             int received = 0;
  7.             byte[] receiveBuf =  new byte[BUFSiZE];
  8.             while(true){
  9.                 Socket socket = serverSocket.accept();
  10.                 SocketAddress clientAddress = socket.getRemoteSocketAddress();
  11.                 System.out.println(“handling client at:”+clientAddress);
  12.                 InputStream in = socket.getInputStream();
  13.                 OutputStream out = socket.getOutputStream();
  14.                 while((received=in.read(receiveBuf))!=-1){
  15.                     out.write(receiveBuf,0,received);
  16.                 }
  17.                 socket.close();
  18.             }
  19.         } catch (IOException e) {
  20.             e.printStackTrace();
  21.         }
  22.     }
  23. }

输出结果:

客户端:Connecting to server……
received:Echo this!

服务端:handling client at:/127.0.0.1:50884

标签