javasocket编程实现聊天程序
时间: 2023-11-30 12:38:44 浏览: 87
Java Socket编程可以实现基于网络的聊天程序。下面是一个简单的示例代码:
```java
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("客户端说:" + line);
writer.println("服务器回应:" + line);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
}
}
```
```java
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器,IP地址为:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = consoleReader.readLine()) != null) {
writer.println(line);
System.out.println("服务器回应:" + reader.readLine());
}
consoleReader.close();
reader.close();
writer.close();
socket.close();
}
}
```
以上代码实现了一个简单的聊天程序,客户端和服务器端通过Socket建立连接,通过输入输出流进行通信。
阅读全文