用java编写程序,实现基于TCP/IP协议的Socket通信过程。服务器端开放: IP地址:127.0.0.1 端口号:8889 客户端发送数据: Hello Server!
时间: 2024-03-23 22:40:11 浏览: 55
好的,以下是Java代码实现:
服务器端:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8889, 10, InetAddress.getByName("127.0.0.1"));
System.out.println("服务器已启动,等待客户端连接...");
} catch (IOException e) {
System.out.println("服务器启动异常:" + e.getMessage());
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("客户端连接成功,地址为:" + clientSocket.getInetAddress().getHostAddress());
} catch (IOException e) {
System.out.println("客户端连接异常:" + e.getMessage());
System.exit(1);
}
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("客户端发送数据:" + inputLine);
out.println("服务端已收到数据:" + inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("127.0.0.1", 8889);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("未知的主机地址:" + e.getMessage());
System.exit(1);
} catch (IOException e) {
System.out.println("无法连接到服务器:" + e.getMessage());
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("发送数据:" + userInput);
System.out.println("服务端返回数据:" + in.readLine());
if (userInput.equals("Bye.")) {
break;
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
当客户端运行后,输入"Hello Server!",即可与服务器进行通信。
阅读全文