seara 发表于 2013-2-3 11:24:20

Java网络编程从入门到精通(27):关闭服务端连接

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Word.Document"><meta name="Generator" content="Microsoft Word 11"><meta name="Originator" content="Microsoft Word 11"><link rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C02%5Cclip_filelist.xml"><!--><xml>Normal07.8 磅02falsefalsefalseMicrosoftInternetExplorer4</xml><!--><!--><!--><style><!--/* Font Definitions */@font-face{font-family:宋体;panose-1:2 1 6 0 3 1 1 1 1 1;}@font-face{font-family:""@宋体";panose-1:2 1 6 0 3 1 1 1 1 1;}/* Style Definitions */p.MsoNormal, li.MsoNormal, div.MsoNormal{mso-style-parent:"";margin:0cm;margin-bottom:.0001pt;text-align:justify;text-justify:inter-ideograph;font-size:10.5pt;font-family:"Times New Roman";}/* Page Definitions */@page{}@page Section1{size:612.0pt 792.0pt;margin:72.0pt 90.0pt 72.0pt 90.0pt;}div.Section1{page:Section1;}--></style><!--><style>/* Style Definitions */table.MsoNormalTable{mso-style-parent:"";font-size:10.0pt;font-family:"Times New Roman";mso-fareast-font-family:"Times New Roman";}</style><!-->本文为原创,如需转载,请注明作者和出处,谢谢!

上一篇:Java网络编程从入门到精通(26):在服务端接收和发送数据

在客户端和服务端的数据交互完成后,一般需要关闭网络连接。对于服务端来说,需要关闭Socket和ServerSocket。
在关闭Socket后,客户端并不会马上感知自已的Socket已经关闭,也就是说,在服务端的Socket关闭后,客户端的Socket的isClosed和isConnected方法仍然会分别得到false和true。但对已关闭的Socket的输入输出流进行操作会抛出一个SocketException异常。
在关闭服务端的ServerSocket后,ServerSocket对象所绑定的端口被释放。这时客户端将无法连接服务端程序。下面的代码演示了在服务端关闭Socket后,客户端是所何反应的。

<div style="border: 1px solid #cccccc; padding: 4px 5px 4px 4px; background-color: #eeeeee; font-size: 13px; width: 98%;"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->package server;

importjava.net.*;

classClient
{
publicstaticvoidmain(String[]args)throwsException
{
Socketsocket=newSocket("127.0.0.1",1234);
Thread.sleep(1000);
//socket.getOutputStream().write(1);
System.out.println("read()="+socket.getInputStream().read());
System.out.println("isConnected()="+socket.isConnected());
System.out.println("isClosed()="+socket.isClosed());
}
}
publicclassCloseSocket
{
publicstaticvoidmain(String[]args)throwsException
{
ServerSocketserverSocket=newServerSocket(1234);
while(true)
{
Socketsocket=serverSocket.accept();
socket.close();
}
}
}
页: [1]
查看完整版本: Java网络编程从入门到精通(27):关闭服务端连接