用java编写程序,实现基于TCP/IP协议的Socket通信过程。服务器端开放: IP地址:127.0.0.1 端口号:8889 客户端发送数据: Hello Server!
时间: 2024-03-06 11:47:05 浏览: 105
好的,我可以帮您解答这个问题。
以下是服务器端的Java代码示例:
```java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
int portNumber = 8889;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
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("Received message from client: " + inputLine);
out.println("Server received your message: " + inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
```
以下是客户端的Java代码示例:
```java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
String hostName = "127.0.0.1";
int portNumber = 8889;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server response: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
```
您可以先运行服务器端程序,然后再运行客户端程序,在客户端程序中输入"Hello Server!",就可以发送数据给服务器端了。服务器端程序会接收到数据并返回相应的信息给客户端,客户端会输出服务器端返回的信息。
阅读全文