Java写一个socket服务端和客户端
时间: 2023-10-07 20:07:05 浏览: 106
java socket服务端和客户端
以下是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对象,绑定端口号为8888
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("无法在端口8888上创建ServerSocket对象。");
System.exit(-1);
}
Socket clientSocket = null;
try {
// 监听客户端连接请求,等待客户端连接
System.out.println("等待客户端连接...");
clientSocket = serverSocket.accept();
System.out.println("客户端已连接。");
} catch (IOException e) {
System.err.println("无法接受客户端连接请求。");
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("客户端:" + inputLine);
out.println("服务端已接收到消息:" + 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 echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// 创建Socket对象,连接到服务端的8888端口
echoSocket = new Socket("localhost", 8888);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("无法连接到主机:localhost。");
System.exit(-1);
} catch (IOException e) {
System.err.println("无法获得I/O流。");
System.exit(-1);
}
// 向服务端发送消息,并接收回复
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("服务端:" + in.readLine());
}
// 关闭资源
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
```
上述代码实现了一个简单的回显服务,客户端发送一条消息,服务端收到后再回复一条消息。你可以参考这个示例代码来编写更复杂的socket程序。
阅读全文