如何实现服务器端支持多个客户端同时工作?秘籍就是:在服务器端利用多线程。
客户端:
import java.io.*; import java.net.*; /** * Socket客户端 * 功能为:发送字符串“Hello”到服务器端,并打印出服务器端的反馈 */ public class MulSocketClient { public static void main(String[] args) { Socket socket = null; InputStream is = null; OutputStream os = null; //服务器端IP地址 String serverIP = "127.0.0.1"; //服务器端端口号 int port = 10000; //发送内容 String data[] ={"First","Second","Third"}; try { //建立连接 socket = new Socket(serverIP,port); //初始化流 os = socket.getOutputStream(); is = socket.getInputStream(); byte[] b = new byte[1024]; for(int i = 0;i < data.length;i++){ //发送数据 os.write(data[i].getBytes()); //接收数据 int n = is.read(b); //输出反馈数据 System.out.println("服务器反馈:" + new String(b,0,n)); } } catch (Exception e) { e.printStackTrace(); //打印异常信息 }finally{ try { //关闭流和连接 is.close(); os.close(); socket.close(); } catch (Exception e2) {} } } }
服务器端:
import java.net.ServerSocket; import java.net.Socket; /** * 支持多客户端的服务器端实现 */ public class MulThreadSocketServer { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; //监听端口号 int port = 10000; try { //建立连接 serverSocket = new ServerSocket(port); System.out.println("服务器已启动:"); while(true){ //获得连接 socket = serverSocket.accept(); //启动线程 new LogicThread(socket); } } catch (Exception e) { e.printStackTrace(); }finally{ try{ //关闭连接 serverSocket.close(); }catch(Exception e){} } } }
服务器端多线程类:
import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class LogicThread extends Thread { Socket socket; InputStream is; OutputStream os; public LogicThread(Socket socket){ this.socket = socket; start(); //启动线程 } public void run(){ byte[] b = new byte[1024]; try{ //初始化流 os = socket.getOutputStream(); is = socket.getInputStream(); for(int i = 0;i < 3;i++){ //读取数据 int n = is.read(b); //逻辑处理 byte[] response = logic(b,0,n); //反馈数据 os.write(response); } }catch(Exception e){ e.printStackTrace(); }finally{ close(); } } /** * 关闭流和连接 */ private void close(){ try{ //关闭流和连接 os.close(); is.close(); socket.close(); }catch(Exception e){} } /** * 逻辑处理方法,实现echo逻辑 * @param b 客户端发送数据缓冲区 * @param off 起始下标 * @param len 有效数据长度 * @return */ private byte[] logic(byte[] b,int off,int len){ byte[] response = new byte[len]; //将有效数据拷贝到数组response中 System.arraycopy(b, 0, response, 0, len); return response; } }