public static void main(String[] args)throws Exception{
//建立socket对象,指定服务端的
Socket s = new Socket(InetAddress.getLocalHost(),10006);
//得到输出流,向服务端写数据
OutputStream out = s.getOutputStream();
out.write("Hi, server, I'm client.".getBytes());
//得到输入流,读取服务端返回的数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
}
复制代码
异常信息:
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at com.itheima.TcpServer.main(TcpServer.java:17)作者: 沫然 时间: 2014-4-8 01:10 本帖最后由 沫然 于 2014-4-8 01:12 编辑
通常都是在说是要使用的端口被别的程序已经使用
你把端口改一下
短时间内new socket操作过多
而socket.close()操作并不能立即释放绑定的端口
而是把端口设置为TIME_WAIT状态
过段时间(默认240s)才释放(用netstat -na可以看到)
最后系统资源耗尽
(windows上是耗尽了pool of ephemeral ports 这段区间在1024-5000之间)