serversocket - clientsocket新建对象的对应关系
Socket编程中,采用下面方式创建server和client,则会拒绝连接
1 // socket服务端创建,端口号大于1023,连接队列默认50,此处显式给为65,超过拒绝连接,采用InetAddress对象传入IP地址 2 InetAddress address = InetAddress.getLocalHost(); 3 ServerSocket server = new ServerSocket(8080, 65, address);
// socket客户端,连接服务端IP和端口 String host = "127.0.0.1"; int port = 8080; Socket socket = null; try { socket = new Socket(host, port); } catch (IOException e) { e.printStackTrace(); }
报错如下:


注意:
1 只有给出实际的IP地址才可以实现连接,而不能用“127.0.0.1”。或者采用下面的方式:
InetAddress address = InetAddress.getLocalHost();
int port = 8080; Socket socket = null; try { socket = new Socket(address, port);
} catch (IOException e) { e.printStackTrace(); }
2.采用如下方式新建serversocket对象,客户端才可以用127.0.0.1+port建立连接:
ServerSocket server = null; InetAddress address = null; try { // 服务端socket监听端口为8080,连接的队列长度最大为66,超过就拒绝,服务器IP地址 server = new ServerSocket(8080, 3); System.out.println("server is read for connection!"); } catch (IOException e) { e.printStackTrace(); }
浙公网安备 33010602011771号