当我们搭建了一个Socket服务端,是需要去响应多用户的访问的。此时,我们就要使用多线程,为每个访问的用户建立一个线程来响应该用户的访问。
具体实现,看如下代码:
package com.sun.socket;
import Java.io.IOException;
import java.NET.*;
import java.io.*;
import java.util.*;
public class ServerSocketDemo {
ArrayList MSG = new ArrayList<>();
ArrayList RES = new ArrayList<>();
public void init(){
MSG.add("hellow");
RES.add("hi");
}
public void test1(){
init();
ServerSocket server = null;
try{
//以指定端口搭建一个Socket服务端
server = new ServerSocket(12000);
//等待客户端Socket实例,并创建一个线程去响应该客户单实例
while(true){
new Response(server.accept()).start();;
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
server.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
public String getMsg(String msg){
String res = "Are you kidding me?Please speak English.";
for(int i=1;i
1、我们可以写一个小小测试工具类,来测试一下public String getMsg(String msg)方法。
对该类右键,选择new新建一个JUnit Test Case 。
package com.sun.socket;
import org.junit.Assert;
import org.junit.Test;
public class ServerSocketDemoTest {
@Test
public void testGetMsg() {
try{
//调用该方法,并与其目标值进行对比。
String msg = new ServerSocketDemo().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)设置属性,点击运行就可以进行压力测试了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



