客户端连服务端,服务端在客户端连接成功后 把连接关闭。客户端依然在不停的read。没抛异常。这个时候应该抛异常呀。。客户端代码
public static void main(String[] args) throws InterruptedException {
String hostname = "localhost";
Socket connection = null;
byte[] receiveBuffer = new byte[2*1024];
while(true){
try {
connection = new Socket(hostname, 1111);
InputStream input = connection.getInputStream();
int count = 0;
while(count<10)
{
System.out.println(new Timestamp(System.currentTimeMillis()));
Thread.sleep(100);
count++;
int bytesRead = input.read(receiveBuffer, 0, 2*1024);
System.out.println(bytesRead);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务端代码
public static void main(String[] args) { try {
ServerSocket server = new ServerSocket(1111);
while (true) {
Socket connection = server.accept();
System.out.println("Accepting connections on port "
+ connection.getLocalPort());
System.out.println("Accepting connections remote port "
+ connection.getPort());
if (connection != null)
{
System.out.println(new Timestamp(System.currentTimeMillis()));
connection.close();
}
}
} // end try catch (IOException ex) { System.err.println(ex); }
public static void main(String[] args) throws InterruptedException {
String hostname = "localhost";
Socket connection = null;
byte[] receiveBuffer = new byte[2*1024];
while(true){
try {
connection = new Socket(hostname, 1111);
InputStream input = connection.getInputStream();
int count = 0;
while(count<10)
{
System.out.println(new Timestamp(System.currentTimeMillis()));
Thread.sleep(100);
count++;
int bytesRead = input.read(receiveBuffer, 0, 2*1024);
System.out.println(bytesRead);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务端代码
public static void main(String[] args) { try {
ServerSocket server = new ServerSocket(1111);
while (true) {
Socket connection = server.accept();
System.out.println("Accepting connections on port "
+ connection.getLocalPort());
System.out.println("Accepting connections remote port "
+ connection.getPort());
if (connection != null)
{
System.out.println(new Timestamp(System.currentTimeMillis()));
connection.close();
}
}
} // end try catch (IOException ex) { System.err.println(ex); }
解决方案 »
- java中怎么实现动态构造甘特图
- 请问我用了System.arraycopy,要import什么呀?
- 求java web工程下数据库配置文件加密问题
- 请教各路前辈~~~~~~~~~~~~
- e.getSouce()的问题
- 初学JAVA,请问大哥们,JAVA用什么IDE比较好?谢谢!!!
- 如何更改java的输出信息默认语言(日语->英语)
- 类似于weicf01提的问题,大三学生,不知如何选择?
- 请问如何通过JFileChooser类获取某个目录而非某个文件
- 英文不是很好,为了考SCJP,好多地方看英文书,概念什么的比较模糊,哪有详细的中文的Java语言教程呀?最好和SCJP想符合的,别告诉我《Think in Java》呀!那本书我烦透了!
- JAVA初级的线程问题。
- 在此程序中问什么获取不到 图像的URL
因为while(true)