java搭建一个Socket服务器响应多用户访问

作者:袖梨 2022-06-29

当我们搭建了一个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)设置属性,点击运行就可以进行压力测试了。

这里写图片描述

相关文章

精彩推荐