当我们搭建了一个Socket服务端,是需要去响应多用户的访问的。此时,我们就要使用多线程,为每个访问的用户建立一个线程来响应该用户的访问。
具体实现,看如下代码:
| 代码如下 | 复制代码 |
|
packagecom.sun.socket; importJava.io.IOException; importjava.NET.*; importjava.io.*; importjava.util.*;
/** * Description: * 搭建一个Socket服务器响应多用户访问 * @author Lee * */ publicclassServerSocketDemo { ArrayList MSG =newArrayList(); ArrayList RES =newArrayList();
/** * Description: * 初始化数据 * */ publicvoidinit(){ MSG.add("hellow"); RES.add("hi"); }
/** * Description: * 搭建一个Socket服务器响应多个用户访问 * */ publicvoidtest1(){ init(); ServerSocket server =null;
try{ //以指定端口搭建一个Socket服务端 server =newServerSocket(12000);
//等待客户端Socket实例,并创建一个线程去响应该客户单实例 while(true){ newResponse(server.accept()).start();; }
}catch(IOException e){ e.printStackTrace(); }finally{ try{ server.close(); }catch(IOException e){ e.printStackTrace(); }
} }
/** * Description: * 根据用户输入的内容,返回相应的内容 * * @param msg 客户端输入的内容 * @return 返回服务端回复的内容 * */ publicString getMsg(String msg){ String res ="Are you kidding me?Please speak English.";
for(inti=1;i if(msg.contains(MSG.get(i))){ res = RES.get(i); } } returnres; } publicstaticvoidmain(String[] args) { // TODO Auto-generated method stub newServerSocketDemo().test1(); } /** * Description: * 响应用户 * @author Lee * */ classResponseextendsThread{ Socket client; /** * Description: * 默认构造器 * */ publicResponse(){} /** * Description: * 初始化Socket * */ publicResponse(Socket client){ this.client = client; } @Override publicvoidrun(){ Scanner input =null; PrintWriter output =null; try{ //获取用户端的输入和输出流 input =newScanner(client.getInputStream()); output =newPrintWriter(client.getOutputStream()); output.println("欢迎访问!"); output.flush(); //等待客户端的输入 String content =null; while(input.hasNext()){ content = input.nextLine(); //根据用户端的输入,做出相应的反应 if(content.equalsIgnoreCase("quit")){ break; }else{ output.println(getMsg(content)); output.flush(); } } }catch(IOException e){ e.printStackTrace(); }finally{ //关闭资源 input.close(); output.close(); } } } } | |
1、我们可以写一个小小测试工具类,来测试一下public String getMsg(String msg)方法。
对该类右键,选择new新建一个JUnit Test Case 。
| 代码如下 | 复制代码 |
|
packagecom.sun.socket; importorg.junit.Assert; importorg.junit.Test; publicclassServerSocketDemoTest { @Test publicvoidtestGetMsg() { try{ //调用该方法,并与其目标值进行对比。 String msg =newServerSocketDemo().getMsg("在吗"); Assert.assertEquals("gun!", msg);
}catch(Exception e){ e.printStackTrace(); } }
} | |
2、使用apche JMeter工具对该服务端进行压力测试
(1)打开Apache JMeter,右键测试计划->添加->Threads(Users)->Setup Thread Group
(2)设置线程属性(线程数,循环次等)
(3)右键添加->simpler->HTTP请求
(4)设置属性,点击运行就可以进行压力测试了。
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环