编写基于TCP的网络应用程序 【要求】 实现客户端和服务器端的双向数据传输。两人一组完成测试。用Java程序编写
时间: 2024-03-20 21:40:53 浏览: 88
好的,我可以为你提供一份基于Java语言编写的基于TCP的网络应用程序示例。代码如下:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection.....");
clientSocket = serverSocket.accept();
System.out.println("Connection established with: " + clientSocket.getInetAddress().getHostName());
} 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()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println(stdIn.readLine());
}
out.close();
in.close();
stdIn.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try {
echoSocket = new Socket("localhost", 8888);
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);
}
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
```
这里我们以服务端监听本地的8888端口,客户端连接localhost的8888端口为例。建立连接后,双方可进行数据传输,每次客户端发送数据后,服务端会返回一条信息。
你可以在两台计算机上分别运行以上代码,尝试进行双向数据传输的测试。
阅读全文