客户端服务器端实现双向通信

港控/mmm° 2022-08-24 04:09 373阅读 0赞
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. public class TcpServer
  7. {
  8. public static void main(String args[]) throws Exception
  9. {
  10. ServerSocket ss=new ServerSocket(5000);
  11. Socket socket=ss.accept();
  12. InputStream is=socket.getInputStream();
  13. byte[]by=new byte[1024];
  14. Thread.sleep((long)Math.random()*3000);
  15. int length=is.read(by);
  16. System.out.println(new String(by,0,length));
  17. //while(-1!=(is.read(by)))
  18. //{
  19. //System.out.println(new String(by));
  20. //}
  21. OutputStream os=socket.getOutputStream();
  22. byte[]b=new byte[1000];
  23. b="nice to meet you too!".getBytes();
  24. os.write(b);
  25. os.close();
  26. is.close();
  27. }
  28. }
  29. //这种双向通信必须要服务器首先开启监听模块,客户端进行连接通信,通信过程中输入输出的顺序给定后,不能更改
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.OutputStream;
  33. import java.net.Socket;
  34. import java.net.UnknownHostException;
  35. public class TcpClient
  36. {
  37. public static void main(String args[]) throws Exception
  38. {
  39. Socket socket1=new Socket("localhost",5000);
  40. OutputStream os=socket1.getOutputStream();
  41. byte []b=new byte[1000];
  42. String str="hello,nice to meet you!";
  43. b=str.getBytes();
  44. os.write(b);
  45. InputStream is=socket1.getInputStream();
  46. byte []by=new byte[1024];
  47. // while(-1!=(is.read(by)))
  48. // {
  49. // System.out.println(new String(by));
  50. // }
  51. int length=is.read(by);
  52. System.out.println(new String(by,0,length));
  53. os.close();
  54. is.close();
  55. }
  56. }

发表评论

表情:
评论列表 (有 0 条评论,373人围观)

还没有评论,来说两句吧...

相关阅读