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