用Java写一个socket tcp 通讯程序
时间: 2023-09-16 13:11:56 浏览: 91
好的,以下是一个简单的Java Socket TCP通讯程序的示例代码:
服务端代码:
```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(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 client to connect...");
clientSocket = serverSocket.accept();
System.out.println("Client connected: " + 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()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
outputLine = "Server response: " + inputLine;
out.println(outputLine);
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("localhost", 8888);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.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);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
String response = in.readLine();
System.out.println("Server: " + response);
if (userInput.equals("bye")) {
break;
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
这个示例程序中,服务端监听本地的8888端口,客户端连接到本地的8888端口,发送数据给服务端,服务端收到数据后回复客户端,直到客户端发送"bye"后断开连接。您可以根据自己的需求修改代码,实现您自己的Socket通讯程序。
阅读全文