Socket类主要在处理客户端的Socket连线,如果要实现一个服务器,可以使用ServerSocket类,它包括了服务器倾听与客户端连线的方法,您可以用数种方式来指定ServerSocket构造函数:
public ServerSocket(int port)
public ServerSocket(int port, int queuelength)
public ServerSocket(int port, int queuelength, InetAddress bindAddress)
以上的建构式皆需处理IOException, SecurityException,port是所指定要系结(bind)的连接埠,而queuelength用来指定外来连线的伫列长度,bindAddress指定要系结至哪一个网路接口。
ServerSocket拥有Socket类取得相关信息的能力,例如:
public InetAddress getInetAddress()
public int getLocalPort()
当要倾听连线或关闭连线时,可以使用accept()与close()方法:
public Socket accept()
public void close()
这两个方法需处理IOException,其中accept()传回的是有关连线客户端的Socket对象信息,可以用它来取得客户端的连线信息,或关闭客户端的连线。
下面这个程序是个简单的Echo服务器,您可以使用Telnet程序,或是 Socket 类 所实现的程序来测试它,它会将客户端的文字指令再传回客户端,客户端输入/bye可结束连线:
package onlyfun.caterpillar;
import java.io.*; import java.net.*;
public class EchoServer { public static void main(String[] args) { final int port = 7; ServerSocket serverSkt; Socket skt; BufferedReader sktReader; String message; PrintStream sktStream; try { serverSkt = new ServerSocket(port); try { while(true) { System.out.printf("连接埠 %d 接受连线中......%n", port); skt = serverSkt.accept(); System.out.printf("与 %s 建立连线%n", skt.getInetAddress().toString());
sktReader = new BufferedReader(new InputStreamReader(skt.getInputStream()));
while((message = sktReader.readLine()) != null) { if(message.equals("/bye")) { System.out.println("Bye!"); skt.close(); break; }
System.out.printf("Client: %s%n", message); sktStream = new PrintStream(skt.getOutputStream()); sktStream.printf("echo: %s%n", message); } } } catch(IOException e) { System.out.println(e.toString()); } } catch(IOException e) { System.out.println(e.toString()); } } }
假设使用Telnet程序连线至Echo服务器,并输入以下的内容:
$ telnet localhost 7
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello! Echo Test!
echo: Hello! Echo Test!
哈啰!中文测试!
echo: 哈啰!中文测试!
/bye
Connection closed by foreign host.
|
以下是Echo服务器的回应:
$ java echoServer
连接埠 7 接受连线中......
与/127.0.0.1建立连线
client say: Hello! Echo Test!
client say: 哈啰!中文测试!
Bye!
连接埠 7 接受连线中......
|
|