Socket
套接字(socket)是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元。它是网络通信过程中端点的抽象表示包含进行网络通信必须的五种信息:连接使用的协议(主要分tcpsocket 和udpsocket),本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程的协议端口。简单的说就是服务端和客户端通信的一个轨道。
Server Socket
我们要创建一个Socket连接,前提必须要有一个连接目标Server Socket,Server
Socket主要功能是建立服务端端口监听,随时处理来时Client 的Socket连接请求。我们平时的测试过程中,Server Socket 信息就是被测服务的ip和监听端口,建立Server Socket方法如下:
ServerSocket server=new ServerSocket(6789);
Socket流程
在了解Server Socket后我们就可以轻松的建立Socket连接,和服务端进行通信并测试服务端的功能。下图为一个完整的Socket流程:
Socket 封装:
public String execute(String host, int port, String request) {
long begin = System.currentTimeMillis();
try {
Socket socket = new Socket(host, port);
System.out.println("send+++++++++++>");
System.out.println("请求字符串:"+request);
//打开输出流
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
//发送字节数组流长度
output.writeInt(request.getBytes("utf-8").length);
//发送字节数组流内容
output.write(request.getBytes("utf-8"));
output.flush();
//打开输入流
input = new DataInputStream(socket.getInputStream());
int length = input.readInt();
byte[] bytes = new byte[length];
//读取服务端返回的字节数组流
input.readFully(bytes, 0, length);
long end =System.currentTimeMillis();
<span style="white-space:pre"> </span> System.out.println("total time:" + (end - begin) + "ms");
return new String(bytes,"UTF-8");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(socket !=null || dos !=null ){
input.close();
dos.close();
socket.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
下面是一个获取验证码完整的例子:
cmd | getAuthCode | ||
名称 | 类型 | 必需 | 说明 |
userName | string | 是 | 用户名 |
authCodeType | int | 否 | 1、注册2;忘记密码3、修改手机号码4、登陆 |
public class GetCode extends BaseCase{
public String host="192.168.1.10";
public int port=12345;
@Test
public void test1(){
String ss="{\"authCodeType\":4,\"cmd\":\"getAuthCode\",\"userName\":\"13600136123\"}";
System.out.println(excete(host, port, ss));
}
}
执行完毕的结果:
total time:19ms
{"cmd":"getAuthCode","code":"00000","errCode":"","errMsg":"","msg":"","success":true}
{"cmd":"getAuthCode","code":"00000","errCode":"","errMsg":"","msg":"","success":true}
备注:部分只是来源于其它同学