java socket聊天
时间: 2023-06-29 22:07:33 浏览: 99
Java Socket 聊天是一种基于网络 Socket 编程的聊天应用程序。它可以让两个或多个用户通过网络实时通信、聊天。下面是一个简单的 Java Socket 聊天程序的示例:
服务端代码:
```java
import java.net.*;
import java.io.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10007);
} catch (IOException e) {
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection...");
clientSocket = serverSocket.accept();
System.out.println("Connection established with: " + 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;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.net.*;
import java.io.*;
public class ChatClient {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 10007);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.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: " + in.readLine());
if (userInput.equals("Bye."))
break;
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
这个示例中,服务端监听本地的 10007 端口,客户端连接到服务端的该端口。当客户端连接成功后,客户端和服务端之间可以互相发送消息。
你可以在控制台中输入消息并发送到服务端,服务端会将接收到的消息打印到控制台中,然后将消息发送回客户端,客户端将接收到的消息打印到控制台中。
以上是一个简单的 Java Socket 聊天程序示例,你可以根据自己的需求进行修改和扩展。
阅读全文