[关闭]
@gzm1997 2018-06-05T16:39:45.000000Z 字数 1614 阅读 975

java socket编程

java


java的socket编程跟python的很像 而且也很方便 简单记录一下 同时server那边的accept也是阻塞的

connect函数可以在初始化一个socket对象之后 一般客户端可以用来链接服务端 但是如果在socket构造函数那里传入serverName和port 也是可以在初始化的时候进行连接的

服务端

  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. public class JServer extends Thread {
  7. private ServerSocket server;
  8. public JServer(int port) throws IOException {
  9. server = new ServerSocket(port);
  10. server.setSoTimeout(10000);
  11. }
  12. public void run() {
  13. while (true) {
  14. try {
  15. System.out.println("等待客户端连接");
  16. Socket s = server.accept();
  17. System.out.println("远程连接地址 " + s.getRemoteSocketAddress());
  18. DataInputStream in = new DataInputStream(s.getInputStream());
  19. System.out.println("接受数据" + in.readUTF());
  20. DataOutputStream out = new DataOutputStream(s.getOutputStream());
  21. out.writeUTF("我接收到了 拜拜");
  22. s.close();
  23. } catch (IOException i) {
  24. i.printStackTrace();
  25. }
  26. }
  27. }
  28. public static void main(String[] args) throws IOException {
  29. JServer JS = new JServer(5000);
  30. JS.run();
  31. }
  32. }

客户端

  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.net.Socket;
  5. public class JClient extends Thread {
  6. private Socket client;
  7. public JClient(String serverName, int port) throws IOException {
  8. client = new Socket(serverName, port);
  9. }
  10. public void run() {
  11. try {
  12. System.out.println("现在开始连接服务端");
  13. DataOutputStream out = new DataOutputStream(client.getOutputStream());
  14. out.writeUTF("我是客户端 服务端你那边接收到我发的信息了没");
  15. DataInputStream in = new DataInputStream(client.getInputStream());
  16. System.out.println("从服务端接受到 " + in.readUTF());
  17. client.close();
  18. } catch (IOException i) {
  19. i.printStackTrace();
  20. }
  21. }
  22. public static void main(String[] args) throws IOException {
  23. JClient client = new JClient("127.0.0.1", 5000);
  24. client.run();
  25. }
  26. }

结果
image_1cf7fbt5l1flia2gpmn1bp1328p.png-192.9kB
image_1cf7fcgan62o1ict1n4lvbbda16.png-160.3kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注