java客户端发送socket消息到指定服务并接收响应
做个笔记
/**
* 发送socket到指定服务
* 接收有6位报文头长度的响应,支持读取分包
*
* @param host IP
* @param port 端口
* @param msg 消息内容,自己加报文头长度哦
* @return
* @throws Exception
*/
public static String send(String host, String port, String msg) throws Exception {
System.out.println("socket发送,host=" + host + ",port=" + port + ",msg=" + msg);
try (Socket socket = new Socket(host, Integer.parseInt(port));) {
OutputStream os = socket.getOutputStream();
os.write(msg.getBytes());
System.out.println("=======已成功发送=======");
InputStream is = socket.getInputStream();
StringBuilder ret = new StringBuilder();
//这里每次读的长度可以自己改
byte[] bys = new byte[1024];
int len = 0;
//6代表长度头的长度
byte[] headBytes = new byte[6];
int headRead = is.read(headBytes);
String head = new String(headBytes, 0, headRead, StandardCharsets.UTF_8);
ret.append(head);
System.out.println("head=" + head);
int headLength = Integer.parseInt(head);
int current = 0;
while (true) {
len = is.read(bys);
current = current + len;
if (len == 0) {
continue;
}
if (len == -1) {
break;
}
String str = new String(bys, 0, len, StandardCharsets.UTF_8);
ret.append(str);
if (current == headLength) {
break;
}
}
//输出数据
System.out.println("socket接收,host=" + host + ",port=" + port + ",msg=" + ret.toString());
//释放资源
socket.close();
return ret.toString();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("发送失败");
}
}
本文作者:DaenMax
本文链接:https://www.cnblogs.com/daen/p/17359418.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步