1. 服务端
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public void start(){
try {
ServerSocket serverSocket = new ServerSocket(1000);
while(true){
Socket client = serverSocket.accept();
System.out.println("client -- > ip : " + client.getInetAddress().getHostAddress() + ", port : " + client.getPort());
DataInputStream dis = new DataInputStream(client.getInputStream());
System.out.println(dis.readInt());
BufferedReader d = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(new String(d.readLine()));
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TcpServer().start();
}
}
2. 客户端
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 1000);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeInt(100);
dos.write("你好".getBytes());
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}