TCP客户端代码
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
InputStream is = null;
BufferedReader reader = null;
try {
// 1. 要知道服务器的地址、端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 2. 创建一个Socket连接
socket = new Socket(serverIP, port);
// 3. 创建输出流,用于发送消息给服务器
os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
// 4. 创建输入流,用于接收服务器的消息
is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// 5. 客户端输入消息
reader = new BufferedReader(new InputStreamReader(System.in));
String clientMessage;
String serverResponse;
while (true) {
// 读取客户端输入的消息
System.out.print("客户端: ");
clientMessage = reader.readLine();
// 发送消息到服务器
pw.println(clientMessage);
// 接收服务器返回的消息
serverResponse = br.readLine();
System.out.println("服务器: " + serverResponse);
// 判断是否退出
if ("bye".equalsIgnoreCase(clientMessage)) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (reader != null) reader.close();
if (is != null) is.close();
if (os != null) os.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
TCP服务器代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
try {
// 1. 创建一个服务器端的Socket,绑定端口9999
serverSocket = new ServerSocket(9999);
// 2. 等待客户端连接
System.out.println("服务器等待连接...");
socket = serverSocket.accept();
System.out.println("客户端已连接!");
// 3. 获取客户端发送的消息
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
// 4. 创建输出流,发送消息给客户端
os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
String clientMessage;
String serverMessage;
while (true) {
// 读取客户端发送的消息
clientMessage = br.readLine();
System.out.println("客户端: " + clientMessage);
// 判断是否退出
if ("bye".equalsIgnoreCase(clientMessage)) {
pw.println("再见!");
break;
}
// 服务器回复消息
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("服务器: ");
serverMessage = reader.readLine();
// 发送回复给客户端
pw.println(serverMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (br != null) br.close();
if (is != null) is.close();
if (os != null) os.close();
if (socket != null) socket.close();
if (serverSocket != null) serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}