用java写一个可以发送和接收得socket客户端和服务端例子
时间: 2023-11-06 20:07:01 浏览: 164
好的,以下是一个简单的Java Socket客户端和服务端的例子:
服务端代码:
```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(8080); // 监听8080端口
} catch (IOException e) {
System.err.println("Could not listen on port: 8080.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection...");
clientSocket = serverSocket.accept(); // 等待客户端连接
System.out.println("Connected to client: " + clientSocket.getInetAddress().getHostName());
} 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("Received from client: " + inputLine);
out.println("Server received: " + inputLine); // 发送回复给客户端
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
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", 8080); // 连接到本地8080端口
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("Received from server: " + in.readLine()); // 接收服务器的回复
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
这个例子中,服务端监听8080端口,等待客户端连接。一旦客户端连接上来,服务端会接收客户端发送的消息,并将收到的消息回复给客户端。客户端连接到本地的8080端口,向服务端发送消息,并接收服务端的回复。
阅读全文