用JAVA基于SOCKET的局域网实现一对一通信
时间: 2023-12-18 12:02:37 浏览: 83
用Java Socket实现一个简单的基于P2P范型的即时聊天系统。
好的,下面是一个基于 SOCKET 的局域网一对一通信的 JAVA 代码示例:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端说:" + message);
writer.println("服务端已收到消息:" + message);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 9999);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("请输入消息:");
String message = consoleReader.readLine();
writer.println(message);
String response = reader.readLine();
System.out.println("服务端说:" + response);
}
//reader.close();
//writer.close();
//socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上是一个简单的基于 SOCKET 的局域网一对一通信的 JAVA 代码示例。在实际开发过程中,还需要考虑异常处理、线程安全、协议设计等问题,并根据具体需求进行功能扩展。
阅读全文