聊天室 java代码_java聊天室的实现代码
时间: 2023-07-02 09:15:35 浏览: 100
以下是一个基于 Java 实现的简单聊天室代码:
Server.java
```
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(9000);
} catch (IOException e) {
System.err.println("Could not listen on port: 9000.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for client...");
clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
outputLine = "Welcome to the Chat Room!"; // Welcome message
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println("Client message: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
Client.java
```
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
clientSocket = new Socket("localhost", 9000);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server message: " + in.readLine());
if (userInput.equals("Bye."))
break;
}
out.close();
in.close();
stdIn.close();
clientSocket.close();
}
}
```
这只是一个简单的实现,如果需要实现更复杂的聊天功能,还需要进行更多的开发工作。
阅读全文