分布式通信-tcp/ip socket
Socket通讯的过程
Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。
对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:
(1) 创建Socket;
(2) 打开连接到Socket的输入/出流;
(3) 按照一定的协议对Socket进行读/写操作;
(4) 关闭Socket.
服务端
/** * 单播 */ public class SocketServer { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); //监听客户端 System.out.println("start server"); //从buffer读取内容 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(bufferedReader.readLine()); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); }finally { if(serverSocket!=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
客户端
public class SocketClient { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); System.out.println("start client"); printWriter.print("hello"); printWriter.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }