用JavaSocket编程实现白板程序
时间: 2024-03-03 20:49:19 浏览: 99
JavaSocket编程可以用于实现白板程序的客户端和服务器之间的通信。以下是一个简单的JavaSocket白板程序实现的示例代码:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
new ServerThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} 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", 8888);
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Hello, server!\n");
out.flush();
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例程序中,服务器端监听本地的8888端口,等待客户端连接。当有客户端连接时,创建一个新的线程来处理客户端的请求。客户端连接到服务器的localhost:8888地址,并向服务器发送一条消息。服务器接收到消息后,在控制台上输出。客户端接收到来自服务器的消息后,在控制台上输出。这个示例程序只是一个简单的实现,实际使用时需要根据具体需求进行修改和完善。
阅读全文