六、多客户端连接服务器
上面的服务器端程序一次只能连接一个客户端,这在实际应用中显然是不可能的。通常的网络环境是多个客户端连接到某个主机进行通讯,所以我们要对上面的程序进行改造。
设计思路:服务器端主程序监听某一个端口,客户端发起连接请求,服务器端主程序接收请求,同时构造一个线程类,用于接管会话。当一个Socket会话产生后,这个会话就会交给线程进行处理,主程序继续进行监听。
下面的实现程序流程是:客户端和服务器建立连接,客户端发送消息,服务端根据消息进行处理并返回消息,若客户端申请关闭,则服务器关闭此连接,双方通讯结束。
客户端程序:- package sock;
-
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
-
- public class SocketClient {
- public static void main(String[] args) {
- try {
- Socket socket =new Socket("127.0.0.1",2013);
- socket.setSoTimeout(60000);
-
- PrintWriter printWriter =new PrintWriter(socket.getOutputStream(),true);
- BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(socket.getInputStream()));
-
- String result ="";
- while(result.indexOf("bye") == -1){
- BufferedReader sysBuff =new BufferedReader(new InputStreamReader(System.in));
- printWriter.println(sysBuff.readLine());
- printWriter.flush();
-
- result = bufferedReader.readLine();
- System.out.println("Server say : " + result);
- }
-
- printWriter.close();
- bufferedReader.close();
- socket.close();
- }catch (Exception e) {
- System.out.println("Exception:" + e);
- }
- }
- }
复制代码
服务器端程序:
- package sock;
- import java.io.*;
- import java.net.*;
-
- public class Server extends ServerSocket {
- private static final int SERVER_PORT =2013;
-
- public Server()throws IOException {
- super(SERVER_PORT);
-
- try {
- while (true) {
- Socket socket = accept();
- new CreateServerThread(socket);//当有请求时,启一个线程处理
- }
- }catch (IOException e) {
- }finally {
- close();
- }
- }
-
- //线程类
- class CreateServerThread extends Thread {
- private Socket client;
- private BufferedReader bufferedReader;
- private PrintWriter printWriter;
-
- public CreateServerThread(Socket s)throws IOException {
- client = s;
-
- bufferedReader =new BufferedReader(new InputStreamReader(client.getInputStream()));
-
- printWriter =new PrintWriter(client.getOutputStream(),true);
- System.out.println("Client(" + getName() +") come in...");
-
- start();
- }
-
- public void run() {
- try {
- String line = bufferedReader.readLine();
-
- while (!line.equals("bye")) {
- printWriter.println("continue, Client(" + getName() +")!");
- line = bufferedReader.readLine();
- System.out.println("Client(" + getName() +") say: " + line);
- }
- printWriter.println("bye, Client(" + getName() +")!");
-
- System.out.println("Client(" + getName() +") exit!");
- printWriter.close();
- bufferedReader.close();
- client.close();
- }catch (IOException e) {
- }
- }
- }
-
- public static void main(String[] args)throws IOException {
- new Server();
- }
- }
复制代码 |
|