@gzm1997
2018-06-05T08:39:45.000000Z
字数 1614
阅读 1214
java
java的socket编程跟python的很像 而且也很方便 简单记录一下 同时server那边的accept也是阻塞的
connect函数可以在初始化一个socket对象之后 一般客户端可以用来链接服务端 但是如果在socket构造函数那里传入serverName和port 也是可以在初始化的时候进行连接的
服务端
import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class JServer extends Thread {private ServerSocket server;public JServer(int port) throws IOException {server = new ServerSocket(port);server.setSoTimeout(10000);}public void run() {while (true) {try {System.out.println("等待客户端连接");Socket s = server.accept();System.out.println("远程连接地址 " + s.getRemoteSocketAddress());DataInputStream in = new DataInputStream(s.getInputStream());System.out.println("接受数据" + in.readUTF());DataOutputStream out = new DataOutputStream(s.getOutputStream());out.writeUTF("我接收到了 拜拜");s.close();} catch (IOException i) {i.printStackTrace();}}}public static void main(String[] args) throws IOException {JServer JS = new JServer(5000);JS.run();}}
客户端
import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;public class JClient extends Thread {private Socket client;public JClient(String serverName, int port) throws IOException {client = new Socket(serverName, port);}public void run() {try {System.out.println("现在开始连接服务端");DataOutputStream out = new DataOutputStream(client.getOutputStream());out.writeUTF("我是客户端 服务端你那边接收到我发的信息了没");DataInputStream in = new DataInputStream(client.getInputStream());System.out.println("从服务端接受到 " + in.readUTF());client.close();} catch (IOException i) {i.printStackTrace();}}public static void main(String[] args) throws IOException {JClient client = new JClient("127.0.0.1", 5000);client.run();}}
结果

