當前位置:編程學習大全網 - 源碼下載 - java如何通過TCP發送字符串和整型數據組成的報文?

java如何通過TCP發送字符串和整型數據組成的報文?

在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());

}

}

}

在這個例子中,服務器在接收到客戶端發送的字符串和整數後,會打印出來,然後返回修改過的整數。客戶端在接收到服務器返回的字符串和整數後,也會打印出來。

  • 上一篇:如果妳需要購置壹臺電腦,應怎麽樣選擇其配置?包括哪些技術指標
  • 下一篇:沈陽燃放煙花爆竹規定2022
  • copyright 2024編程學習大全網