java如何通过TCP发送字符串和整型数据组成的报文?

哪位知道,java如何通过TCP发送字符串和整型数据组成的报文?
最新回答
捣碎幻觉

2024-11-04 07:37:40

在Java中,你可以使用Socket和ServerSocket类来通过TCP发送和接收数据。以下是一个简单的例子,它展示了如何发送字符串和整数数据。
首先,这是一个服务器端的代码:
java复制代码
import java.io.*;
import java.net.*;

public class TCPServer {
public static void main(String args[]) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server is listening on port 8080");

Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");

DataInputStream in = new DataInputStream(clientSocket.getInputStream());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

String receivedString = in.readUTF();
int receivedInt = in.readInt();

System.out.println("Received string: " + receivedString);
System.out.println("Received int: " + receivedInt);

out.writeUTF("String received");
out.writeInt(receivedInt * 2);

in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port 8080 or listening for a connection");
System.out.println("Server exception: " + e.getMessage());
}
}
}
然后,这是一个客户端的代码:
java复制代码
import java.io.*;
import java.net.*;

public class TCPClient {
public static void main(String args[]) {
try {
Socket socket = new Socket("localhost", 8080);
System.out.println("Connected to server");

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());

out.writeUTF("Hello Server");
out.writeInt(123);

String receivedString = in.readUTF();
int receivedInt = in.readInt();

System.out.println("Received string: " + receivedString);
System.out.println("Received int: " + receivedInt);

in.close();
out.close();
socket.close();
} catch (IOException e) {
System.out.println("Exception caught while trying to connect to server");
System.out.println("Client exception: " + e.getMessage());
}
}
}
在这个例子中,服务器在接收到客户端发送的字符串和整数后,会打印出来,然后返回修改过的整数。客户端在接收到服务器返回的字符串和整数后,也会打印出来。