用Java socket实现客户端和服务端对话代码
时间: 2023-10-07 17:13:41 浏览: 60
以下是一个简单的 Java Socket 实现客户端和服务端对话的示例代码:
服务端代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
socket.getOutputStream().write(message.getBytes());
byte[] buffer = new byte[1024];
int len = socket.getInputStream().read(buffer);
System.out.println("Client: " + new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
Scanner scanner = new Scanner(System.in);
while (true) {
byte[] buffer = new byte[1024];
int len = socket.getInputStream().read(buffer);
System.out.println("Server: " + new String(buffer, 0, len));
String message = scanner.nextLine();
socket.getOutputStream().write(message.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上是一个简单的 Java Socket 实现客户端和服务端对话的示例代码,仅供参考。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)