TCP :java.net.ServerSocket 、 java.net.Socket
步骤、创建服务端和客户端
一、创建服务端:使用ServerSocket类
1、用 ServerSocket 创建服务器,指定端口
2、接收客户端连接,阻塞式等待
3、连接好了之后, 使用输出流发送数据到套接字(一块公共区域)
4、释放资源
二、创建客户端:使用Socket类
1、用 Socket 创建客户端,指定服务端的IP地址和端口号,此时就是在建立连接
2、连接好了之后,使用输入流接收套接字(一块公共区域)的数据
3、释放资源
三、服务端java代码
public class MyTCPService {
public static void main(String[] args) {
try {
// 1、用 ServerSocket 创建服务器,指定端口
ServerSocket serverSocket = new ServerSocket(8888);
// 2、接收客户端连接,阻塞式等待
Socket client = serverSocket.accept();
System.out.println("一个客户端建立了连接");
// 3、连接好了之后, 使用输出流发送数据到套接字(一块公共区域)
String sendMsg = "welcome";
DataOutputStream outputStream = new DataOutputStream(client.getOutputStream());
outputStream.writeUTF(sendMsg);
outputStream.flush();
// 4、释放资源
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、客户端java代码
public class MyTCPClient {
public static void main(String[] args) {
try {
// 1、用 Socket 创建客户端,指定服务端的IP地址和端口号,此时就是在建立连接
Socket client = new Socket("localhost", 8888);
// 2、连接好了之后,使用输入流接收套接字(一块公共区域)的数据
DataInputStream inputStream = new DataInputStream(client.getInputStream());
System.out.println(inputStream.readUTF());
// 3、释放资源
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}