1 . 服务器端
public class Server {
public static void main(String[] args) {
try {
// 1. 绑定端口,并监听此端口
ServerSocket serverSocket = new ServerSocket(6000);
System.out.println("服务器启动成功...");
// 2. 调用accept()方法开始监听,等待客户端的链接
// 使accept()阻塞等待客户端请求,有客户请求到来则产生一个Socket对象,并继续执行
Socket socket = serverSocket.accept();
// 3. 获取输入流,并调取客户端信息
// 由socket对象得到输入流,并构造相应的BufferedReader对象
String line;
InputStream inputStream = socket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
// 4. 由socket对象得到输出流,并构造PrintWriter对象
PrintWriter writer = new PrintWriter(socket.getOutputStream());
// 5. 由系统的标准输入设备构造BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 6. 从标准输入打印从客户端度读入的字符串
line = br.readLine();
while(!line.endsWith("end")){
writer.println(line);
writer.flush();
System.out.println("Server: " + line);
System.out.println("Client: " + in.readLine());
line = br.readLine();
}
// 7. 释放
writer.close();
in.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("服务器启动失败...");
}
}
}
- 客户端
public class Client {
public static void main(String[] args) {
try {
// 1. 创建客户端Socket,指定服务器地址和端口
Socket socket = new Socket("127.0.0.1", 6000);
System.out.println("客户端启动成功...");
// 2. 获取输出流, 向服务器发送消息
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
// 3. 获取输入流,并读取服务器端的响应信息
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readLine;
readLine = br.readLine();
while(!readLine.equals("end")){
writer.println(readLine);
writer.flush();
System.out.println("Client: " + readLine);
System.out.println("Server: " + in.readLine());
readLine = br.readLine();
}
// 4. 释放资源
writer.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("未知主机");
} catch (IOException e) {
e.printStackTrace();
System.out.println("客户端启动失败");
}
}
}
- 运行时首先开启服务器端,再打开客户端。在客户端控制台中输入消息,接下来在服务器端控制台数输入消息,可以看到客户端发送的消息。