Java实现tcp套接字编程实现聊天
时间: 2025-01-10 11:12:13 浏览: 38
### Java TCP Socket Programming Example for Chat Application
For creating a simple chat application using Java, one needs to understand how client-server communication works over TCP. In this setup, the server listens for incoming connections from clients and handles messages sent by them.
#### Server-Side Code Implementation
Below is an example of setting up a basic server that accepts multiple clients:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static void main(String[] args) throws IOException {
int port = 12345; // Port number where server will listen
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Chat Server started on port " + port);
while (true) {
Socket socket = serverSocket.accept(); // Accepts incoming client requests
// Handle each client request in separate thread
ClientHandler handler = new ClientHandler(socket);
Thread t = new Thread(handler);
t.start();
}
} catch (IOException e) {
System.err.println("Could not start server");
e.printStackTrace();
}
}
private static class ClientHandler implements Runnable {
private final Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (
BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter outputWriter = new PrintWriter(socket.getOutputStream(), true)
) {
String message;
while ((message = inputReader.readLine()) != null && !message.equalsIgnoreCase("bye")) {
System.out.println("Received: " + message);
outputWriter.println(message.toUpperCase()); // Echo back uppercase version
if ("exit".equalsIgnoreCase(message.trim())) break;
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {}
}
}
}
}
```
This implementation sets up a `ChatServer` listening at specified port[^1]. Each time a client connects via `accept`, a new instance of `ClientHandler` runs as its own thread handling I/O operations independently without blocking others[^4].
#### Client-Side Code Implementation
Here’s what the corresponding client-side looks like when connecting to such servers:
```java
import java.io.*;
import java.net.Socket;
public class ChatClient {
public static void main(String[] args) {
String hostname = "localhost";
int port = 12345;
try (
Socket socket = new Socket(hostname, port);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
) {
System.out.print("> ");
String line;
while((line=userInput.readLine())!=null){
writer.write(line+"\n");writer.flush();
if(line.equals("exit")){
break;
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
```
In this snippet, after establishing connection through `new Socket(...)`, standard streams are wrapped around sockets' input/output channels allowing bidirectional data exchange.
阅读全文
相关推荐


















