首页 > 编程 > Java > 正文

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

2019-11-26 13:04:45
字体:
来源:转载
供稿:网友

当我们搭建了一个Socket服务端,是需要去响应多用户的访问的。此时,我们就要使用多线程,为每个访问的用户建立一个线程来响应该用户的访问。

具体实现,看如下代码:

package com.sun.socket; import Java.io.IOException; import java.NET.*; import java.io.*; import java.util.*;/** * Description: * 搭建一个Socket服务器响应多用户访问 * @author Lee * */ public class ServerSocketDemo { ArrayList MSG = new ArrayList<>(); ArrayList RES = new ArrayList<>();/** * Description: * 初始化数据 * */public void init(){  MSG.add("hellow");  RES.add("hi");}/** * Description: * 搭建一个Socket服务器响应多个用户访问 * */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();    }  }}/** * Description: * 根据用户输入的内容,返回相应的内容 *  * @param msg 客户端输入的内容 * @return 返回服务端回复的内容 * */public String getMsg(String msg){  String res = "Are you kidding me?Please speak English.";  for(int i=1;i<MSG.size();i++){    if(msg.contains(MSG.get(i))){      res = RES.get(i);    }  }  return res;}public static void main(String[] args) {  // TODO Auto-generated method stub  new ServerSocketDemo().test1();}/** * Description: * 响应用户 * @author Lee * */class Response extends Thread{  Socket client;  /**   * Description:   * 默认构造器    * */  public Response(){}  /**   * Description:   * 初始化Socket   * */  public Response(Socket client){    this.client = client;  }  @Override  public void run(){    Scanner input = null;    PrintWriter output = null;    try{      //获取用户端的输入和输出流      input = new Scanner(client.getInputStream());      output = new PrintWriter(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 。

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

这里写图片描述

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表