用以监听来自客户机的连接。每当有一个新的客户机连 接时,ServerSocket就会创建一个新的Socket类实例,同时服务器也将创建一新 线程,即一个Connection 对象,以处理基于Socket 的通信。与客户机的所有通 信均由这个Connection 对象处理。Connection的构造函数将初始化基于Socket 对象的通信流,并启动线程的运行。与客户机 的通信以及服务的提供,均由 Connection对象处理。
(3)、客户机首先创建一Socket对象,用以与服务器通信。之后需创建两个 对象:DataInputStream 和PrintStream,前者用以从Socket 的InputStream 输 入流中读取数据,后者则用于往Socket的OutputStream 中写数据。最后,客户 机程序从标准输入(如:控制台)中读取数据,并把这些数据写到服务器,在从 服务器读取应答消息,然后把这些应答消息写到准输出。
以下分别为服务器和客户机端的源程序清单。本程序在NT 4.0 网络环境 (TCP/IP)下使用JDK1.1 调试通过。
Java?úClient/Serverí????Dμ?ó|ó?(2)
ê±??:2010-12-11
èy?¢±àD′·t???÷ààJava3ìDò
// Server.java
???? import java.io.*;
???? import java.net.*;
???? public class Server extends Thread
???? {
???? public final static int Default_Port=6543;
???? protectd int port;
???? protectd ServerSockt listen_socket;
???? // ?¨ò?3?′íày3ì£oè?1?3???òì3£′í?ó£?í?3?3ìDò?£
???? Public static void fail(Exception e, String msg)
???? {
???? System.err.println(msg + ": " + e);
???? System.exit(1);
???? }
???? // ?¨ò?2¢???ˉ·t???÷μ?Socket ày3ì£??àìy?í?§?úμ?á??ó???ó?£
???? public Server(int port)
???? {
???? if(port == 0) port = Default_Port;
???? this.port = port;
???? try
???? {
???? listen_socket = new ServerSocket(port);
???? }
???? catch(IOException e) fail(e, "Exception creating server socket");
???? System.out.println("Server: listening on port" + port);
???? This.start();
???? }
???? /* ?????a·t???÷?àìy??3ìμ??÷3ìDò?£????3ìò??±?-?·?′DD£??àìy2¢?óêü?í ?§?ú·¢3?μ?á??ó
???? ???ó?£????ò???á??ó£??ù2úéúò???á??ó???óó?????ó|£?í¨1ySocket í¨μà?? DDí¨D??£*/
???? public void run()
???? {
???? try
???? {
???? while(true)
???? {
???? Socket client_socket = listen_socket.accept();
???? Connection c = new Connection(client_socket);
???? }
???? }
???? catch(IOException e) fail(e,"Exception while listening for connections")
???? }
???? // ???ˉ·t???÷?÷3ìDò
???? public static void main(String args[])
???? {
???? int port = 0;
???? if (args.length == 1)
???? {
???? try port = Integer.parseInt(args[0]);
???? catch(NumberFormatException e) port = 0;
???? }
???? new Server(port);
???? }???????????????????????????????????????????? // End of the main
???? }???????????????????????????????????? // End of Server class
???? //ò????¨ò?á?Connection àà£??üê?ó?à′′|àíó??í?§?úμ??ùóDí¨D?μ???3ì?£
???? class Connection extends Thread
???? {
???? protected Socket client;
???? protected DataInputStream in;
???? protected PrintStream out;
???? // 3?ê??ˉí¨D?á÷2¢???ˉ??3ì
???? public Connection(Socket client_socket)
???? {
???? client = client_soc
|