当我们搭建了一个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
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)设置属性,点击运行就可以进行压力测试了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
希望与广大网友互动??
点此进行留言吧!