今晚上开始研究java的网络编程,先从socket开始吧。下面是一个简单的client/server的例子:
客户端代码:
public class TCPECHOClient { public static void main(String[] args) { String server = "localhost"; String data = "Echo this!"; byte[] bs = data.getBytes(); try { Socket socket = new Socket(server,80); System.out.println("Connecting to server……"); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(bs); int totalDateRecived = 0; int bytesRecvd = 0 ; while(totalDateRecived<bs.length){ totalDateRecived +=bytesRecvd; if((bytesRecvd=in.read(bs,totalDateRecived,bs.length-totalDateRecived))==-1) throw new SocketException("connection closed!"); } System.out.println("received:"+new String(bs)); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
服务端:
public class TCPEchoServer { private static int BUFSiZE = 32; public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(80); int received = 0; byte[] receiveBuf = new byte[BUFSiZE]; while(true){ Socket socket = serverSocket.accept(); SocketAddress clientAddress = socket.getRemoteSocketAddress(); System.out.println("handling client at:"+clientAddress); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); while((received=in.read(receiveBuf))!=-1){ out.write(receiveBuf,0,received); } socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
客户端:Connecting to server……
received:Echo this!
服务端:handling client at:/127.0.0.1:50884