API:
服务器端:SocketServer 和 Socket
SocketServer server = new SocketServer(9999); //在本机上创建一个socket服务器,端口是9999
Socket socket = server.accept()//接受客户端发来的socket连接,此方法是阻塞式的,会一直等待客户端的连接请求
//in 和 out 是socket通信的核心,可以使用各种包装类包装他们。
//in 的read方法是阻塞式的,应用时需要注意。
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedInputStream
BufferedOutputStream
BufferedWriter writer = new BufferedWriert(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
客户端:Socket
Socket socket = new Socket("localhost",9999);//根据主机地址和端口号以TCP/IP协议形式 发送连接请求并建立连接
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
...
模拟Http协议
Socket socket = new Socket("www.baidu.com",80);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));