TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,创建服务器端程序,设置监听器端口
package com.zhangjie.socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
//接受客户端的请求
while(true){
Socket s = ss.accept();
System.out.println("A client connect!\n");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2,创建客户端代码,向服务器程序发送数据
package com.zhangjie.socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",6666);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello Servier");
dos.flush();
dos.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印结果:
A client connect!
Hello Servier
A client connect!
Hello Servier |
|