首先,這是壹個服務器端的代碼:
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());
}
}
}
在這個例子中,服務器在接收到客戶端發送的字符串和整數後,會打印出來,然後返回修改過的整數。客戶端在接收到服務器返回的字符串和整數後,也會打印出來。