javasocket白板程序
时间: 2023-08-05 20:36:06 浏览: 101
基于JavaSocket多客户端并发通信聊天程序的设计与实现
Java Socket是一种在Java编程语言中提供的API,用于实现网络通信。白板程序是指可以在多个用户之间共享画板,实现实时绘图的应用程序。
下面是一个简单的Java Socket白板程序的示例:
1. 服务器端代码:
```java
import java.io.*;
import java.net.*;
public class WhiteboardServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for client...");
clientSocket = serverSocket.accept();
System.out.println("Client connected.");
} catch (IOException e) {
System.err.println("Accept failed.");
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("Client: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
2. 客户端代码:
```java
import java.io.*;
import java.net.*;
public class WhiteboardClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server: " + in.readLine());
if (userInput.equals("Bye.")) {
break;
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
```
这个白板程序的实现方式是:客户端向服务器发送消息,服务器原封不动地将消息返回给客户端。在实际应用中,可以将消息解析为绘图指令,并在客户端的画板上进行绘制。
阅读全文