所谓socket,我们理解为“插座”。服务器端一“插”,客户端一“插”,即实现了通信的通路,那么如何形成链接呢?
客户端:
Socket s = null;
try {
s = new Socket("127.0.0.1",8555); //参数内是所连接服务器端的IP地址和接口,服务器端会有进程在这个端口上进行监听
System.out.println("connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
服务器端:
try {
ServerSocket ss = new ServerSocket(8555);//这里与客户端申请的接口必须一致
while(true){
Socket s = ss.accept();//接受客户端申请的连接
System.out.println("a client connected!");
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
System.out.println(str);
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} |