欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Socket 网络编程:支持多客户端连接的Demo示例

程序员文章站 2024-03-23 09:53:22
...

在Java的网络编程中,一般分为Server端和Client端。Server端提供服务,Client端请求服务。那么如果Server端仅支持单个客户端,这显然无法满足日常需求。

前文已经讲述了简单的Java Socket编程示例,该示例仅支持单客户端链接。为此,本文对该示例进行了改进,使其可以同时服务多个客户端。

其中Client端代码不变,如下所示:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {
	
	//默认端口号
	private String ip = null;
	private int port = 8888;
	

	public SocketClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	public boolean startClient() {
		
		try {
			
			Socket socket = new Socket(ip,port);
	        InputStream isockets = socket.getInputStream();
	        OutputStream osockets = socket.getOutputStream();
	        
	        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(osockets));
	        //向服务器端发送一条消息
	        bw.write("test\n");
	        bw.flush();
	        
	        //读取服务器返回的消息
	        BufferedReader br = new BufferedReader(new InputStreamReader(isockets));
	        String mess = br.readLine();
	        System.out.println("Sever Message:"+mess);
	        
	        socket.close();
	        
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return true;
	}
	
	public static void main(String[] args) {
		SocketClient sc = new SocketClient("192.168.226.128",1234);
		sc.startClient();

	}

}

其中,Server端代码,修改为对每个请求连接的客户端,创建一个独立的线程,进行服务。代码如下所示:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
	
	//默认端口号
	private int port = 8888;
	private ServerSocket server;
	
	public SocketServer(int port) {
		super();
		this.port = port;
	}
	//每个客户端由独立的线程进行处理
	public class SocketClientHandler extends Thread{
		 
	    private Socket client;
	    
	    public SocketClientHandler(Socket client){
	        this.client = client;
	    }
	 
	    @SuppressWarnings("static-access")
		@Override
	    public void run(){
	    	
			 try {
				 
				System.out.println("Client IP: "+client.getInetAddress().getLocalHost()+" is Connected");
				BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
				String message = null;
				 
				 //读取客户端消息
				 while((message = br.readLine())!=null) {
					 
					System.out.println("Client Message : "+message);
					 //返回客户端信息
					bw.write("Received \n");
					bw.flush();
				 }
				 
				 System.out.println("Client is Closed");
				 
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	     }
	}

	public boolean startServer() {
		
		try {
			 server = new ServerSocket(port);
			 System.out.println("Server Started...");
			 Socket socket = null;
			 //等待客户端连接
			 while((socket = server.accept())!= null) {
				 //为每一个客户连接,创建一个全新的线程
				 new SocketClientHandler(socket).start();
				 
			 }
			 
		  } catch (IOException e) {
		     e.printStackTrace();
		  }
		return true;
	}
	

	public static void main(String[] args) {
		SocketServer ss = new SocketServer(1234);
		ss.startServer();
	}

}

有任何问题,欢迎留言讨论!