当前位置:主页 > 网页教程 > 网络编程 > Java教程 > 内容欢迎大家投稿

Java网络编程基础(四) ServerSocket类使用

时间:2009-10-11 20:52来源:未知 作者:大宝库 点击:读取中
阅读工具:字体:

由于SSClient使用了流套接字,所以服务程序也要使用流套接字。

这就要创建一个ServerSocket对象,ServerSocket有几个构造函数,最简单的是ServerSocket(int port),当使用ServerSocket(int port)创建一个ServerSocket对象,port参数传递端口号,这个端口就是服务器监听连接请求的端口,如果在这时出现错误将抛出IOException异常对象,否则将创建ServerSocket对象并开始准备接收连接请求。

接下来服务程序进入无限循环之中,无限循环从调用ServerSocket的accept()方法开始,在调用开始后accept()方法将导致调用线程阻塞直到连接建立。在建立连接后accept()返回一个最近创建的Socket对象,该Socket对象绑定了客户程序的IP地址或端口号。

由于存在单个服务程序与多个客户程序通讯的可能,所以服务程序响应客户程序不应该花很多时间,否则客户程序在得到服务前有可能花很多时间来等待通讯的建立,然而服务程序和客户程序的会话有可能是很长的(这与电话类似),因此为加快对客户程序连接请求的响应,典型的方法是服务器主机运行一个后台线程,这个后台线程处理服务程序和客户程序的通讯。

为了示范我们在上面谈到的慨念并完成SSClient程序,下面我们创建一个SSServer程序,程序将创建一个ServerSocket对象来监听端口10000的连接请求,如果成功服务程序将等待连接输入,开始一个线程处理连接,并响应来自客户程序的命令。下面就是这段程序的代码:

Listing 3: SSServer.java


// SSServer.java

import java.io.*;
import java.net.*;
import java.util.*;

class SSServer
{
 public static void main (String [] args) throws IOException
 { 
  System.out.println ("Server starting...\n");

  // Create a server socket that listens for incoming connection
  // requests on port 10000.

  ServerSocket server = new ServerSocket (10000);

  while (true)
  {
   // Listen for incoming connection requests from client
   // programs, establish a connection, and return a Socket
   // object that redivsents this connection.

   Socket s = server.accept ();

   System.out.println ("Accepting Connection...\n");

   // Start a thread to handle the connection.

   new ServerThread (s).start ();
  }
 }
}

class ServerThread extends Thread
{
 private Socket s;

 ServerThread (Socket s)
 {
  this.s = s;
 }

 public void run ()
 {
  BufferedReader br = null;
  PrintWriter pw = null;

  try
  {
   // Create an input stream reader that chains to the socket's
   // byte-oriented input stream. The input stream reader
   // converts bytes read from the socket to characters. The
   // conversion is based on the platform's default character
   // set.

   InputStreamReader isr;
   isr = new InputStreamReader (s.getInputStream ());

   // Create a buffered reader that chains to the input stream
   // reader. The buffered reader supplies a convenient method
   // for reading entire lines of text.

   br = new BufferedReader (isr);

   // Create a print writer that chains to the socket's byte-
   // oriented output stream. The print writer creates an
   // intermediate output stream writer that converts
   // characters sent to the socket to bytes. The conversion
   // is based on the platform's default character set.

   pw = new PrintWriter (s.getOutputStream (), true);

   // Create a calendar that makes it possible to obtain date
   // and time information.

   Calendar c = Calendar.getInstance ();

 // Because the client program may send multiple commands, a
   // loop is required. Keep looping until the client either
   // explicitly requests termination by sending a command
   // beginning with letters BYE or implicitly requests
   // termination by closing its output stream.

   do
   {
    // Obtain the client program's next command.

    String cmd = br.readLine ();

    // Exit if client program has closed its output stream.

    if (cmd == null)
     break;
  
    // Convert command to uppercase, for ease of comparison.

    cmd = cmd.toUpperCase ();

    // If client program sends BYE command, terminate.

    if (cmd.startsWith ("BYE"))
     break;

    // If client program sends DATE or TIME command, return
    // current date/time to the client program.

    if (cmd.startsWith ("DATE") || cmd.startsWith ("TIME"))
     pw.println (c.getTime ().toString ());

    // If client program sends DOM (Day Of Month) command,
    // return current day of month to the client program.

    if (cmd.startsWith ("DOM"))
     pw.println ("" + c.get (Calendar.DAY_OF_MONTH));

    // If client program sends DOW (Day Of Week) command,(责任编辑:大宝库)



------分隔线----------------------------
推荐内容
  • Java新手入门很重要的几个基本概念

    final类:为防止他人从你的类上派生新类,此类是不可扩展的。 动态调用比静态调用花费...

  • Java主要特性

    1、Java语言是简单的 。Java语言的语法与C语言和C++语言很接近,使得大多数程序员很容...

  • Java语言特点

    Java是一种简单的,面向对象的,分布式的,解释型的,健壮安全的,结构中立的,可移植...

  • 什么是Java?

    Java是由Sun Microsystems公司于1995年5月推出的Java程序设计语言(以下简称Java语言...

  • 编写高效Java代码 java.lang.String类和java.

    养成好的代码编写习惯非常重要,比如正确地、巧妙地运用java.lang.String类和java.uti...

赞助商链接
赞助商链接