java socket编程

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

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

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
}
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();
}
}

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