IM应用是Socket编程的典型案例,下面是通过Java和C#语言两种实现的C/S架构聊天程序Demo。
import java.io.*;
import java.net.*;
public class ChatRoomServer {
public static void main(String[] args) throws Exception {
// Create a server socket on port 1234
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server started...");
// Listen for client connections
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Create a new thread to handle the client
ClientHandler handler = new ClientHandler(clientSocket);
handler.start();
}
}
}
class ClientHandler extends Thread {
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket socket) throws IOException {
clientSocket = socket;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
}
public void run() {
try {
// Send a welcome message to the client
out.println("Welcome to the chat room!");
// Broadcast the client's message to all connected clients
while (true) {
String message = in.readLine();
System.out.println("Received message from " + clientSocket + ": " + message);
for (ClientHandler handler : ChatRoomServer.handlers) {
handler.out.println(message);
}
}
} catch (IOException e) {
System.err.println("Error handling client: " + e);
} finally {
try {
clientSocket.close();
} catch (IOException e) {
// ignore
}
}
}
}
上面的代码创建了一个服务器套接字并监听客户端连接。每个客户端连接都使用ClientHandler类在单独的线程中处理。ClientHandler类从客户端读取消息,并将它们广播给所有连接的客户端。
下面是一个连接到服务器并发送消息的客户端程序的例子:
import java.io.*;
import java.net.*;
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
// Connect to the server on port 1234
Socket socket = new Socket("localhost", 1234);
// Create input and output streams
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Read the welcome message from the server
String welcomeMessage = in.readLine();
System.out.println(welcomeMessage);
// Read messages from the user and send them to the server
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = userInput.readLine();
out.println(message);
}
}
}
上面的代码创建到服务器的套接字连接并读取欢迎消息。然后它从用户读取消息并将它们发送到服务器。
要使用这些程序,请使用javac命令编译它们,并使用java命令运行它们。首先,运行ChatRoomServer程序启动服务器。然后,多次运行ChatRoomClient程序连接到服务器并开始聊天。
IM application is a typical case of Socket programming, the following is through Java and C# language two C/S architecture chat program Demo.
import java.io.*;
import java.net.*;
public class ChatRoomServer {
public static void main(String[] args) throws Exception {
// Create a server socket on port 1234
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server started...");
// Listen for client connections
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Create a new thread to handle the client
ClientHandler handler = new ClientHandler(clientSocket);
handler.start();
}
}
}
class ClientHandler extends Thread {
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket socket) throws IOException {
clientSocket = socket;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
}
public void run() {
try {
// Send a welcome message to the client
out.println("Welcome to the chat room!");
// Broadcast the client's message to all connected clients
while (true) {
String message = in.readLine();
System.out.println("Received message from " + clientSocket + ": " + message);
for (ClientHandler handler : ChatRoomServer.handlers) {
handler.out.println(message);
}
}
} catch (IOException e) {
System.err.println("Error handling client: " + e);
} finally {
try {
clientSocket.close();
} catch (IOException e) {
// ignore
}
}
}
}
The above code creates a server socket and listens for client connections. Each client connection is handled in a separate thread using the ClientHandler class. The ClientHandler class reads messages from the client and broadcasts them to all connected clients.
Here’s an example of a client program that connects to the server and sends messages:
import java.io.*;
import java.net.*;
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
// Connect to the server on port 1234
Socket socket = new Socket("localhost", 1234);
// Create input and output streams
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Read the welcome message from the server
String welcomeMessage = in.readLine();
System.out.println(welcomeMessage);
// Read messages from the user and send them to the server
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = userInput.readLine();
out.println(message);
}
}
}
The above code creates a socket connection to the server and reads the welcome message. It then reads messages from the user and sends them to the server.
To use these programs, compile them using the javac command and run them using the java command. First, run the ChatRoomServer program to start the server. Then, run the ChatRoomClient program multiple times to connect to the server and start chatting.