JAVA利用socket编写一个聊天程序代码
时间: 2024-11-29 21:39:14 浏览: 26
在Java中,使用Socket编程可以创建一个简单的点对点聊天应用程序。以下是创建一个基本的服务器-客户端架构的简略示例:
**服务器端(Server.java):**
```java
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket serverSocket;
public static void main(String[] args) {
try {
// 创建服务器套接字
int port = 8000; // 端口号
serverSocket = new ServerSocket(port);
System.out.println("服务器已启动,监听端口 " + port);
while (true) { // 无限循环接受新连接
Socket clientSocket = serverSocket.accept();
Thread clientThread = new ClientHandler(clientSocket);
clientThread.start(); // 启动新的线程处理每个客户端请求
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientHandler extends Thread {
private Socket socket;
public ClientHandler(Socket s) {
this.socket = s;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // 文本模式
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("收到消息:" + inputLine);
out.println("消息已接收");
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
**客户端(Client.java):**
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String host = "localhost"; // 服务器地址
int port = 8000; // 端口号
try (Socket socket = new Socket(host, port)) {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
out.println(message);
System.out.println("发送的消息:" + message);
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个例子展示了基本的通信流程:服务器通过`accept()`等待客户端连接,并为每个连接创建一个新的线程;客户端通过`connect()`连接到服务器,然后读取和发送消息。
阅读全文