编写程序,完成如下功能:有1台服务器端和10台客户端,服务服务器端向10个客户端发送消息"连接上服务器......",客户端收到消息后在控制台打印出消息,用Java语言实现
时间: 2023-07-15 09:13:18 浏览: 96
以下是一个简单的实现,使用了Java中的Socket和ServerSocket类实现TCP连接:
服务器端代码:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started.");
for (int i = 1; i <= 10; i++) {
Socket client = serverSocket.accept();
System.out.println("Client " + i + " connected.");
OutputStream out = client.getOutputStream();
out.write("Connected to server...".getBytes());
out.flush();
out.close();
}
serverSocket.close();
System.out.println("Server closed.");
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
System.out.println(new String(buffer, 0, len));
in.close();
socket.close();
}
}
```
在运行程序之前,需要先启动服务器端,然后再启动10个客户端。在客户端控制台上将会输出"Connected to server..."消息。
阅读全文