Socket请求

测试时可以直接使用软件工具,比如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;
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值