测试时可以直接使用软件工具,比如SocketTool.exe,也方便
若编程中需要Socket的请求,可以参考如下方法。
/**
* socket连接
*
* @param ip 目标主机地址
* @param port 目标端口
* @param req_msg 报文数据
* @param timeout 超时时间(秒)
* @return
*/
public static String sendSocketMessage(String ip, int port, String req_msg, int timeout) {
Socket socket = null;
InputStream is = null;
byte message[] = null;
DataOutputStream reqData = null;
String respMsg = "";
try {
socket = new Socket(ip, port);
socket.setSoTimeout(timeout * 1000);
byte[] msg = req_msg.getBytes("UTF-8");
reqData = new DataOutputStream(socket.getOutputStream());
reqData.write(msg);
reqData.flush();
is = socket.getInputStream();
message = new byte[2048];
int length = is.read(message);
respMsg = respMsg + new String(message, 0, length, "UTF-8");
} catch (UnknownHostException e) {
System.out.println("socket连接UnknownHostException:" + e);
} catch (IOException e) {
System.out.println("socket连接异常 :" + e);
} finally {
try {
if (null != is)
is.close();
if (null != reqData)
reqData.close();
if (null != socket)
socket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
return respMsg;
}