前言:
上一篇讲解了客户端给服务器发送消息,这一篇讲解客户端和服务器相互发送消息,客户端发送消息给服务器,服务器收到客户端的请求然后返回信息给客户端。
1.服务器代码:
** * @author: njb * @Date: 2020/11/28 18:49 * @desc: 服务器socket */ public class ServerSocket { //客户端发送信息 public static void main(String[] args) { OutputStream out = null; Socket socket = null; try { //绑定到本地端口 socket = new Socket("127.0.0.1", 8090); //发送消息 while (true) { System.out.println("=========="); out = socket.getOutputStream(); //输入文字,从控制台输入 Scanner san = new Scanner(System.in); String str = san.next(); System.out.println("我:" + str); out.write(str.getBytes()); out.flush(); //接收信息 InputStream in = socket.getInputStream(); //获取输入流里面数据并存储数据 byte[] b = new byte[1024]; StringBuffer sb = new StringBuffer(); String s; if (in.read(b) != -1) { s = new String(b); System.out.println(s); sb.append(s); } System.out.println("来自服务器的数据:" + sb); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
2.客户端代码:
/** * @author: njb * @Date: 2020/11/28 18:49 * @desc: 客户端socket */ public class ClientSocket { public static void main(String[] args) { ServerSocket server; try { server = new ServerSocket(8090); Socket socket=server.accept(); while(true){ System.out.println("----------"); InputStream in; try { in = socket.getInputStream(); byte [] b=new byte[1024]; StringBuffer sb=new StringBuffer(); String s; if(in.read(b) !=-1){ s=new String(b); sb.append(s); } OutputStream out=socket.getOutputStream(); System.out.println("客户端信息:"+sb); Scanner sc=new Scanner(System.in); String str=sc.next(); System.out.println("我:"+str); out.write(str.getBytes()); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } }