⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 03-套接字编程(上3).htm

📁 这是一个学写JAVA的好东西
💻 HTM
📖 第 1 页 / 共 2 页
字号:
	FONT-SIZE: 12px; COLOR: #333333; LINE-HEIGHT: 19px; TEXT-DECORATION: none}A.navigater:hover {	COLOR: #cc0000}.g1 {	FONT-SIZE: 14px}.g2 {	PADDING-LEFT: 21px; PADDING-TOP: 5px}.g3 {	FONT-WEIGHT: bold; COLOR: #ab6503}.g4 {	COLOR: #ff0000}.img {	BORDER-RIGHT: #800000 1px solid; BORDER-TOP: #800000 1px solid; BORDER-LEFT: #800000 1px solid; BORDER-BOTTOM: #800000 1px solid}.img1 {	BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid}.f14 {	FONT-SIZE: 14px; LINE-HEIGHT: 26px}.f20 {	FONT-WEIGHT: bold; FONT-SIZE: 20px}.top_red {	COLOR: #d70709; TEXT-DECORATION: none}.center01 {	COLOR: #000000; LINE-HEIGHT: 20px}.center01 TD {	COLOR: #000000; LINE-HEIGHT: 20px}.center01 A:link {	COLOR: #000000; TEXT-DECORATION: none}.center01 A:visited {	COLOR: #000000; TEXT-DECORATION: none}.center01 A:hover {	COLOR: #2b7128; TEXT-DECORATION: underline}.center02 {	COLOR: #194e00; LINE-HEIGHT: 20px}.center02 TD {	COLOR: #194e00; LINE-HEIGHT: 20px}.center02 A:link {	COLOR: #194e00; TEXT-DECORATION: none}.center02 A:visited {	COLOR: #194e00; TEXT-DECORATION: none}.center02 A:hover {	COLOR: #194e00; TEXT-DECORATION: underline}--></style><TABLE width=760 border=0 align=center cellPadding=0 cellSpacing=0 bgcolor="#F3F3F3" valign="top">	<tr class="center01"> 		<td width="488" style="padding-left:10px;padding-top:10px">			<a href="index.php">连载</a>       &gt; <a href="slist.php?class1=6">程序设计</a>      &gt; <a href="slist.php?class2=7">Java</a>      &gt; <a href="serialize.php?id=387">Java网络编程专辑</a>		</td>		<td width="280" style="padding-left:10px;padding-top:10px">			<div align="center">			<font color=#0000FF><a href='chapter.php?id=387&volume=3&chapter=2'>上一页</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			<font color=#0000FF><a href="serialize.php?id=387">回书目</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			<font color=#0000FF><a href='chapter.php?id=387&volume=3&chapter=4'>下一页</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			</div>		</td>	</tr>	<tr class="center01">		<td colspan="2" align="center" style="padding-left:10px;padding-top:10px">&nbsp;</td>	</tr>	<TBODY>	<TR> 		<TD colspan="2" align=middle>			<BR>			<div style="FONT-SIZE: 18pt; COLOR: #990000; FONT-FAMILY: 楷体_GB2312" align=center><B>Socket套接字</b></div><br><div style="COLOR: #990000; font-family: ; font-size: 18px;宋体;" align=center>Java套接字编程(上3) </div>			<DIV style="PADDING-RIGHT: 10px; PADDING-LEFT: 10px; FONT-SIZE: 10.5pt; COLOR: black; LINE-HEIGHT: 180%" align=left>                         <br>&nbsp;&nbsp;&nbsp;&nbsp;<P><STRONG>ServerSocket类<BR></STRONG><BR>  由于SSClient使用了流套接字,所以服务程序也要使用流套接字。这就要创建一个ServerSocket对象,ServerSocket有几个构造函数,最简单的是ServerSocket(int port),当使用ServerSocket(int port)创建一个ServerSocket对象,port参数传递端口号,这个端口就是服务器监听连接请求的端口,如果在这时出现错误将抛出IOException异常对象,否则将创建ServerSocket对象并开始准备接收连接请求。<BR><BR>  接下来服务程序进入无限循环之中,无限循环从调用ServerSocket的accept()方法开始,在调用开始后accept()方法将导致调用线程阻塞直到连接建立。在建立连接后accept()返回一个最近创建的Socket对象,该Socket对象绑定了客户程序的IP地址或端口号。<BR><BR>  由于存在单个服务程序与多个客户程序通讯的可能,所以服务程序响应客户程序不应该花很多时间,否则客户程序在得到服务前有可能花很多时间来等待通讯的建立,然而服务程序和客户程序的会话有可能是很长的(这与电话类似),因此为加快对客户程序连接请求的响应,典型的方法是服务器主机运行一个后台线程,这个后台线程处理服务程序和客户程序的通讯。<BR><BR>  为了示范我们在上面谈到的慨念并完成SSClient程序,下面我们创建一个SSServer程序,程序将创建一个ServerSocket对象来监听端口10000的连接请求,如果成功服务程序将等待连接输入,开始一个线程处理连接,并响应来自客户程序的命令。下面就是这段程序的代码:<BR><BR>  Listing 3: SSServer.java<BR><BR></P>
<TABLE width="100%" bgColor=#ffffff>
<TBODY>
<TR>
<TD>// SSServer.java<BR><BR>import java.io.*;<BR>import java.net.*;<BR>import java.util.*;<BR><BR>class SSServer<BR>{<BR> public static void main (String [] args) throws IOException<BR> { <BR>  System.out.println ("Server starting...\n"); <BR><BR>  // Create a server socket that listens for incoming connection<BR>  // requests on port 10000.<BR><BR>  ServerSocket server = new ServerSocket (10000);<BR><BR>  while (true)<BR>  {<BR>   // Listen for incoming connection requests from client<BR>   // programs, establish a connection, and return a Socket<BR>   // object that represents this connection.<BR><BR>   Socket s = server.accept ();<BR><BR>   System.out.println ("Accepting Connection...\n");<BR><BR>   // Start a thread to handle the connection.<BR><BR>   new ServerThread (s).start ();<BR>  }<BR> }<BR>}<BR><BR>class ServerThread extends Thread<BR>{<BR> private Socket s;<BR><BR> ServerThread (Socket s)<BR> {<BR>  this.s = s;<BR> }<BR><BR> public void run ()<BR> {<BR>  BufferedReader br = null;<BR>  PrintWriter pw = null;<BR><BR>  try<BR>  {<BR>   // Create an input stream reader that chains to the socket's<BR>   // byte-oriented input stream. The input stream reader<BR>   // converts bytes read from the socket to characters. The<BR>   // conversion is based on the platform's default character<BR>   // set.<BR><BR>   InputStreamReader isr;<BR>   isr = new InputStreamReader (s.getInputStream ());<BR><BR>   // Create a buffered reader that chains to the input stream<BR>   // reader. The buffered reader supplies a convenient method<BR>   // for reading entire lines of text.<BR><BR>   br = new BufferedReader (isr);<BR><BR>   // Create a print writer that chains to the socket's byte-<BR>   // oriented output stream. The print writer creates an<BR>   // intermediate output stream writer that converts<BR>   // characters sent to the socket to bytes. The conversion<BR>   // is based on the platform's default character set.<BR><BR>   pw = new PrintWriter (s.getOutputStream (), true);<BR><BR>   // Create a calendar that makes it possible to obtain date<BR>   // and time information.<BR><BR>   Calendar c = Calendar.getInstance ();<BR><BR>   // Because the client program may send multiple commands, a<BR>   // loop is required. Keep looping until the client either<BR>   // explicitly requests termination by sending a command<BR>   // beginning with letters BYE or implicitly requests<BR>   // termination by closing its output stream.<BR><BR>   do<BR>   {<BR>    // Obtain the client program's next command.<BR><BR>    String cmd = br.readLine ();<BR><BR>    // Exit if client program has closed its output stream.<BR><BR>    if (cmd == null)<BR>     break;<BR>  <BR>    // Convert command to uppercase, for ease of comparison.<BR><BR>    cmd = cmd.toUpperCase ();<BR><BR>    // If client program sends BYE command, terminate.<BR><BR>    if (cmd.startsWith ("BYE"))<BR>     break;<BR><BR>    // If client program sends DATE or TIME command, return<BR>    // current date/time to the client program.<BR><BR>    if (cmd.startsWith ("DATE") || cmd.startsWith ("TIME"))<BR>     pw.println (c.getTime ().toString ());<BR><BR>    // If client program sends DOM (Day Of Month) command,<BR>    // return current day of month to the client program.<BR><BR>    if (cmd.startsWith ("DOM"))<BR>     pw.println ("" + c.get (Calendar.DAY_OF_MONTH));<BR><BR>    // If client program sends DOW (Day Of Week) command,<BR>    // return current weekday (as a string) to the client<BR>    // program.<BR><BR>    if (cmd.startsWith ("DOW"))<BR>     switch (c.get (Calendar.DAY_OF_WEEK))<BR>    {<BR>     case Calendar.SUNDAY : pw.println ("SUNDAY");<BR>      break;<BR><BR>     case Calendar.MONDAY : pw.println ("MONDAY");<BR>      break;<BR><BR>     case Calendar.TUESDAY : pw.println ("TUESDAY");<BR>      break;<BR><BR>     case Calendar.WEDNESDAY: pw.println ("WEDNESDAY");<BR>      break;<BR><BR>     case Calendar.THURSDAY : pw.println ("THURSDAY");<BR>      break;<BR><BR>     case Calendar.FRIDAY : pw.println ("FRIDAY");<BR>      break;<BR><BR>     case Calendar.SATURDAY : pw.println ("SATURDAY");<BR>    }<BR><BR>    // If client program sends DOY (Day of Year) command,<BR>    // return current day of year to the client program.<BR><BR>    if (cmd.startsWith ("DOY"))<BR>     pw.println ("" + c.get (Calendar.DAY_OF_YEAR));<BR><BR>     // If client program sends PAUSE command, sleep for three<BR>     // seconds.<BR> <BR>    if (cmd.startsWith ("PAUSE"))<BR>    try<BR>    {<BR>     Thread.sleep (3000);<BR>    }<BR>    catch (InterruptedException e)<BR>    {<BR>    }<BR>   }<BR>   while (true);<BR>   {<BR>   catch (IOException e)<BR>   {<BR>    System.out.println (e.toString ());<BR>   }<BR>   finally<BR>   {<BR>    System.out.println ("Closing Connection...\n");<BR><BR>    try<BR>    {<BR>     if (br != null)<BR>      br.close ();<BR><BR>      if (pw != null)<BR>       pw.close ();<BR><BR>      if (s != null)<BR>       s.close ();<BR>    }<BR>    catch (IOException e)<BR>    {<BR>    }<BR>   }<BR>  }<BR>}</TD></TR></TBODY></TABLE><BR>  运行这段程序将得到下面的输出:<BR><BR>
<TABLE width="100%" bgColor=#ffffff>
<TBODY>
<TR>
<TD>Server starting...<BR>Accepting Connection...<BR>Closing Connection...</TD></TR></TBODY></TABLE><BR>  SSServer的源代码声明了一对类:SSServer 和ServerThread;SSServer的main()方法创建了一个ServerSocket对象来监听端口10000上的连接请求,如果成功, SSServer进入一个无限循环中,交替调用ServerSocket的 accept() 方法来等待连接请求,同时启动后台线程处理连接(accept()返回的请求)。线程由ServerThread继承的start()方法开始,并执行ServerThread的run()方法中的代码。<BR><BR>  一旦run()方法运行,线程将创建BufferedReader, PrintWriter和 Calendar对象并进入一个循环,这个循环由读(通过BufferedReader的 readLine())来自客户程序的一行文本开始,文本(命令)存储在cmd引用的string对象中,如果客户程序过早的关闭输出流,会发生什么呢?答案是:cmd将得不到赋值。<BR><BR>  注意必须考虑到这种情况:在服务程序正在读输入流时,客户程序关闭了输出流,如果没有对这种情况进行处理,那么程序将产生异常。<BR><BR>  一旦编译了SSServer的源代码,通过输入Java SSServer来运行程序,在开始运行SSServer后,就可以运行一个或多个SSClient程序。<br><br>          </DIV>		</TD>	</TR>	<TR> 		<TD class=center01>			<div align="center">来源:天极网 作者:<div>		</TD>		<TD width="280" class=center01>			<div align="center">			<font color=#0000FF><a href='chapter.php?id=387&volume=3&chapter=2'>上一页</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			<font color=#0000FF><a href="serialize.php?id=387">回书目</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			<font color=#0000FF><a href='chapter.php?id=387&volume=3&chapter=4'>下一页</a></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			</div>		</TD>	</TR>	</TBODY></TABLE><table><tr><td width="760"> <table width="760" height="10" border="0" cellpadding="0" cellspacing="0">                        <tr>                                <td></td>                        </tr>                </table>                <!------------ 评论 ---------------->                <table width="760" border="0" cellpadding="0" cellspacing="0">                        <tr>                                <td><iframe width="100%" id=vs frameborder=0 scrolling=no src="comment_list1.php?id=387"></iframe>                                </td>                        </tr>                </table><br><script language=javascript>function CheckNetwordForm(theForm){        if("" == theForm.content.value)        {                alert("写两句吧~~");                theForm.content.focus();                return false;        }        var index;        for(index=0;index<theForm.content.value.length;index++)        {                if(" " != theForm.content.value.charAt(index))                        break;        }        if(index == theForm.content.value.length) {                alert("写两句吧~~");                theForm.content.focus();                return false;        }        if (theForm.content.value.length>100){                alert("评论字数不能超过100哦");                theForm.content.focus();                return false;        }        return true;}</script>                <!------------------ 评论 --------------->                <form name=netword method=post action="insertnetword.php" onsubmit="javascript: return CheckNetwordForm(this);">                <table width="760" border="0" cellpadding="0" cellspacing="0">                        <tr>                                <td height="25" class="text6">&nbsp;给此书打分:<a name="1"></a>                                        <select name="score">                                                <option value=5 selected>非常好</option>                                                <option value=4>还凑合</option>                                                <option value=3>一般吧</option>                                                <option value=2>不太行</option>                                                <option value=1>太差了</option>                                        </select> &nbsp; 用户名:                                        <input name="id" value=387 type="hidden" id="id">                                        <input name="backurl" value=/book/chapter.php?id=387&volume=3&chapter=3 type="hidden">                                        <input name="username" type="text" id="username" size="20" maxlength="20">                                        <font color="#666666">*评论字数请控制在一百字以内</font> </td>                        </tr>                </table>                <br>&nbsp;<textarea name="content" cols="80" rows="4" wrap="OFF" id="description"></textarea>                <input type="submit" name="Submit" value="提交">                </form>        </td> </tr></table></td></tr></table> <TABLE cellSpacing=0 cellPadding=0 width=760 border=0>  <TBODY>    <TR>       <TD width="1003" height=9 background=images/t_bj01.gif><IMG height=1     src="images/ccc.gif" width=1></TD>    </TR>  </TBODY></TABLE><TABLE cellSpacing=0 cellPadding=0 width=760 bgColor=#ffffff border=0>  <TBODY>    <TR>       <TD><HR width=760 noShade SIZE=1> </TD>    </TR>    <TR>       <TD align=middle><A class=black href="http://www.chinaren.com/"     target=_blank>ChinaRen</A> - <A class=black     href="http://big5.www.sohu.com/" target=_blank>繁体版</A> - <A class=black     href="http://hr.sohu.com/hrm.html" target=_blank>搜狐招聘</A> - <A class=black     href="http://add.sohu.com/" target=_blank>网站登录</A> - <A class=black     href="http://help.sohu.com/" target=_blank>帮助中心</A> - <A class=black     href="http://book.news.sohu.com/onClick=this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.sohu.com');return"     target=_blank false;>设置首页</A> - <A class=black     href="http://adinfo.sohu.com/" target=_blank>广告服务</A> - <A class=black     href="http://www.sohu.com/about/lianxi.htm" target=_blank>联系方式</A> - <A     class=black href="http://www.sohu.com/about/privacy.html"     target=_blank>保护隐私权</A> - <A class=black href="http://www.sohu.com/about/"     target=_blank>About SOHU</A> - <A class=black     href="http://www.sohu.com/about/" target=_blank>公司介绍</A><BR> <SPAN     class=eng>Copyright &copy; 2004 Sohu.com Inc. All rights reserved. 搜狐公司         版权所有</SPAN> </TD>    </TR>  </TBODY></TABLE></center></body></html><script language="JavaScript" src="http://nielsen.js.sohu.com/nnselect.js"></script><noscript><img src='http://ping.nnselect.com/ping.gif?c=119' height='1' width='1'></noscript>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -