Java TCP通信:模拟服务器与客户端

一时失言乱红尘 2022-05-23 03:16 333阅读 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. public static void main(String[] args) {
  8. try {
  9. ServerSocket ss = new ServerSocket(8889); //指定端口,服务器与客户端要一致
  10. while (true) {
  11. Socket socket = ss.accept(); //等待客户端的接入
  12. System.out.println("the server is listening---" + socket);
  13. System.out.println("服务器端读取数据");
  14. InputStream is = socket.getInputStream(); //建立输入流,读取来自客户端的数据
  15. byte[] bytes = new byte[1024]; //字节流,所以用byte数组存储
  16. int len = 0;
  17. String str = null;
  18. while ((len = is.read(bytes)) != -1) {
  19. str = new String(bytes, 0, len);
  20. System.out.println(str);
  21. }
  22. socket.shutdownInput(); //关闭输入
  23. //String str = "hello world";
  24. str = "I have received:" + str;
  25. OutputStream os = socket.getOutputStream(); //建立字节输出流,将反馈信息发送给客户端
  26. os.write(str.getBytes()); //同样是要用字节的方式
  27. System.out.println("服务端写出数据完毕!");
  28. socket.shutdownOutput();
  29. os.close();
  30. is.close();
  31. socket.close();
  32. if (str.compareTo("quit") == 0)
  33. break;
  34. }
  35. System.out.println("the server will quit...");
  36. ss.close();
  37. } catch (IOException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. }
  42. }

客户端:

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.net.InetAddress;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7. import java.util.Scanner;
  8. public class Tcpclient {
  9. public static void main(String[] args) {
  10. try {
  11. Scanner cin = new Scanner(System.in);
  12. Socket socket=new Socket(InetAddress.getLocalHost(),8889); //连接服务器,通过TCP/IP,指定端口号
  13. System.out.println("客户端:"+socket);
  14. String data= new String();
  15. String stop = "quit";
  16. data = cin.next();
  17. OutputStream os = socket.getOutputStream(); //建立字节输出流
  18. os.write(data.getBytes()); //将输入的内容发送给服务器
  19. System.out.println("键盘输入数据,客户端写出数据完毕!");
  20. socket.shutdownOutput();
  21. System.out.println("客户端读取数据");
  22. InputStream is = socket.getInputStream(); //建立字节输入流
  23. byte[] bytes=new byte[1024];
  24. int len=0;
  25. String str=null;
  26. while((len=is.read(bytes))!=-1)
  27. {
  28. str=new String(bytes,0,len);
  29. System.out.println(str);
  30. }
  31. socket.shutdownInput();
  32. is.close(); //关闭所有的通道
  33. os.close();
  34. socket.close();
  35. } catch (UnknownHostException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. } catch (IOException e) {
  39. // TODO Auto-generated catch block
  40. e.printStackTrace();
  41. }
  42. }
  43. }

20180531215405689

20180531215417135

发表评论

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

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

相关阅读