java socket 通信客户端和服务器端
时间: 2023-07-08 19:52:13 浏览: 107
Java中可以通过Socket实现客户端和服务器端之间的网络通信。下面是一个简单的例子:
服务器端:
```java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection...");
clientSocket = serverSocket.accept();
System.out.println("Connection established with: " + clientSocket.getInetAddress().getHostAddress());
} 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;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message: " + inputLine);
outputLine = "Server received message: " + inputLine;
out.println(outputLine);
if (outputLine.equals("bye"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端:
```java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 8888);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown 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);
String serverResponse = in.readLine();
System.out.println("Server response: " + serverResponse);
if (serverResponse.equals("bye"))
break;
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
以上代码实现了一个简单的客户端和服务器端的通信,可以通过命令行输入消息进行交互。
阅读全文