Java实现 简单聊天软件的源码
时间: 2023-09-29 15:09:46 浏览: 116
一个简单聊天软件源码
好的,下面是一个简单的 Java 聊天室的源码示例,包含服务器端和客户端程序:
1. 服务器端程序
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
private ArrayList<PrintWriter> clientOutputStreams;
public static void main(String[] args) {
new ChatServer().startServer();
}
public void startServer() {
clientOutputStreams = new ArrayList<PrintWriter>();
try {
ServerSocket serverSock = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Got a connection");
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
public void broadcast(String message) {
for (PrintWriter writer : clientOutputStreams) {
writer.println(message);
writer.flush();
}
}
class ClientHandler implements Runnable {
BufferedReader reader;
Socket socket;
public ClientHandler(Socket clientSocket) {
try {
socket = clientSocket;
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(isReader);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
broadcast(message);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
2. 客户端程序
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
new ChatClient().startClient();
}
public void startClient() {
try {
sock = new Socket("127.0.0.1", 5000);
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void sendMessage(String message) {
writer.println(message);
writer.flush();
}
}
```
这是一个简单的 Java 聊天室的实现。如果你想要实现更多的功能,可以根据需求进行修改和扩展。
阅读全文