最简单的TCP编程
服务器端建立连接使用的是ServerSocket,创建对象时需给定服务器端口;客户端建立连接时使用的是Socket,创建对象时需给定连接服务器的IP地址以及端口号;
服务器端:
import java.io.*;import java.net.*;public class TCPServer{public static void main(String[] args) throws Exception{ServerSocket ss = new ServerSocket(6666);while(true){Socket s = ss.accept();System.out.println("a client connect!");DataInputStream dis = new DataInputStream(s.getInputStream());System.out.println(dis.readUTF());dis.close();s.close();}}}
客户端:
import java.io.*;import java.net.*;public class TCPClient{public static void main(String[] args) throws Exception{Socket s = new Socket("127.0.0.1", 6666);OutputStream ops = s.getOutputStream();DataOutputStream dos = new DataOutputStream(ops);dos.writeUTF("I love you!!!");dos.flush();dos.close();s.close();}}
页:
[1]