/** * 发送请求报文 * 注:不可以关闭流 否则会关闭对应的socket */ public static void send(Socket socket, byte[] msg) { DataOutputStream out=null; try { out = new DataOutputStream((socket.getOutputStream())); out.write(msg); out.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 接收服务器返回的报文 * 注:不可以关闭流 否则会关闭对应的socket */ public static byte [] incept(Socket socket) { byte [] head = new byte[4]; byte [] body=null; try { BufferedInputStream bufIn = new BufferedInputStream(socket.getInputStream()); bufIn.read(head); int len1 = Integer.parseInt(new String(head)); body = new byte[len1]; bufIn.read(body); } catch (IOException e) { e.printStackTrace(); } return body; }
简单的socket 示例
Socket service ServerSocket ss = new ServerSocket(8099); System.out.println("服务器已启动,等到客户端的连接..."); Socket socket = ss.accept(); // 服务器收到客户端的数据后,创建与此客户端对话的Socket DataInputStream in = new DataInputStream(socket.getInputStream()); System.out.println("服务器接受到客户端的连接请求:" + in.readUTF());// 用于接收客户端 发来的数据的输入流 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); String sb="hello client"; out.writeUTF(sb.toString());//服务器响应给客户端 socket.close(); ss.close(); Socket client Socket socket = new Socket(); socket.connect(new InetSocketAddress("localhost",8099),1000); socket.setSoTimeout(400); System.out.println("客户端正在连接..."); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); String result = "hello service"; out.writeUTF(result);//把报文结构发送到服务器端 DataInputStream in = new DataInputStream(socket.getInputStream()); String res = in.readUTF();//读取服务器端返回xml System.out.println("读取服务器返回数据:"+res); socket.close();