熟悉课件中基于java的TCP网络通信编程模型图。要求:构建一个可循环接受客户端连接请求的网络服务器,向客户端程序发送内容为:“Hello," + 主机地址 + "port#" + 端口号 + "bye-bye!”,然后关闭与该客户端的连接。客户端程序向服务程序发出连接请求,在连接建立后接收从服务器发过来的信息,在屏幕上打印出来。注意:应先运行服务器,在执行客户端。
时间: 2024-03-18 07:40:12 浏览: 58
好的,这是一个典型的基于Java的TCP服务器编程任务,下面是实现该任务的代码:
服务器端代码:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress() + ":" + socket.getPort());
OutputStream outputStream = socket.getOutputStream();
String message = "Hello," + socket.getInetAddress() + "port#" + socket.getPort() + "bye-bye!";
outputStream.write(message.getBytes("UTF-8"));
outputStream.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器:" + socket.getInetAddress() + ":" + socket.getPort());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String message = new String(buffer, 0, length, "UTF-8");
System.out.println("接收到服务器的信息:" + message);
inputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:在运行客户端之前,应先运行服务器。
阅读全文