2、客户端socket 连接代码。
package com.sokect2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClientT {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
final Socket socket; //定义socket连接对象
try {
socket = new Socket("192.168.94.1",9999);
System.out.println("已经连接到服务器了!");
System.out.println("当前连接的地址为:"+socket.getInetAddress());
System.out.println("当前连接服务器的端口为::"+socket.getPort());
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
throw new IOException("连接服务器出错!,检查连接服务器IP或端口!,或者确认服务器端是否启动!");
}
//回复服务端
new Thread(){
public void run() {
try {
PrintWriter ut = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String readline = in.readLine();
System.out.println(readline);
while(true){
out.println(readline);
System.out.println("客戶端发送消息: " + readline.toString());
readline = in.readLine();
if(readline.equals("bye"))
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
new Thread(){
public void run() {
//获得客户端发来的数据
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
System.out.println("接收服务器发送回来的消息: " + reader.readLine().toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
3、loadrunner中进行测试连接代码。【先启动服务器端代码,然后使用loadrunner进行调用】。
#include "lrs.h" Action()
{
int rc; //存储函数返回值
lrs_startup(257);
lr_start_transaction("Trans_1");
rc=lrs_create_socket("socket0", "TCP", "RemoteHost=192.168.94.1:9999", LrsLastArg);//创建Socket连接
if(rc != 0){
lr_error_message("连接服务器异常,请检查服务器是否启动,或地址是否正确!!");
lr_end_transaction("Trans_1", LR_FAIL);
}else{
lr_output_message("连接到服务器端成功!");
lr_end_transaction("Trans_1", LR_PASS);
}
lrs_close_socket("socket0");
lr_output_message("关闭socket连接成功!!");
return 0;
}
4、执行结果如下图所示。