请用java编写一个服务器端网络程序,实现多线程的TCP网络程序,通过端口8081响应客户端连接,向每一个连接的客户端发送“Hello!”,并编写客户端网络程序进行测试,输出接收到的数据。
时间: 2024-03-05 14:53:05 浏览: 13
好的,以下是Java的示例代码。首先是服务器端的示例代码:
```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(8081);
System.out.println("Listening on 0.0.0.0:8081");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from: " + clientSocket.getInetAddress().getHostAddress());
Thread clientThread = new Thread() {
@Override
public void run() {
try {
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write("Hello!".getBytes());
outputStream.flush();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
clientThread.start();
}
}
}
```
接下来是客户端的示例代码:
```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", 8081);
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
System.out.println("Received: " + new String(buffer, 0, len));
socket.close();
}
}
```
您可以将以上代码保存在两个不同的文件中,分别编译并运行服务器端和客户端程序。当客户端程序运行时,它将连接到服务器端并接收服务器发送的“Hello!”消息。