1、TCP:可靠的需应答的虚拟连接
2、UDP:不可靠不需应答的快速虚拟连接
3、socket:实现server-client连接
- 新建一个Server端socket
import java.net.*; import java.io.*; public class TCPServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(6666); //ServerSocket建立监听端口(port) //无限循环等待连接 while(true) { Socket s = ss.accept();//等待连接,accept()是阻塞试的,但连接上之后才会往下执行 System.out.println("a client connect!"); DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println(dis.readUTF()); dis.close(); //关闭流 s.close(); //关闭socket } } }
- 新建一个Client端socket
import java.net.*; import java.io.*; public class TCPClient { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1", 6666); //建立连接 OutputStream os = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); Thread.sleep(30000); dos.writeUTF("hello server!"); dos.flush(); dos.close(); s.close(); } }