java局域网聊天程序
时间: 2023-11-12 07:58:00 浏览: 98
JAVA局域网聊天程序
3星 · 编辑精心推荐
实现Java局域网聊天程序可以使用Socket编程,具体步骤如下:
1. 创建ServerSocket对象,指定端口号,等待客户端连接。
2. 创建Socket对象,指定服务器IP地址和端口号,连接服务器。
3. 通过输入输出流进行数据传输。
4. 关闭Socket和ServerSocket对象。
以下是一个简单的Java局域网聊天程序的示例代码:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = server.accept();
System.out.println("客户端已连接");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) {
out.println(line);
System.out.println("发送消息:" + line);
System.out.println("接收消息:" + in.readLine());
}
in.close();
out.close();
socket.close();
server.close();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 8888);
System.out.println("已连接服务器");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) {
out.println(line);
System.out.println("发送消息:" + line);
System.out.println("接收消息:" + in.readLine());
}
in.close();
out.close();
socket.close();
}
}
```
阅读全文