socket java 客户端_Java通过Socket实现TCP/IP协议的通信(客户端)

该代码示例展示了如何使用Java的Socket类建立连接,并发送及接收带有报文头和报文体的JSON数据。首先创建Socket连接到指定IP和端口,然后构建JSON对象并转换为字节数组,通过OutputStream发送。同时,从InputStream读取数据,解析长度并获取完整响应。此代码适用于网络通信场景。
摘要由CSDN通过智能技术生成

packagecom.demo.util;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.io.OutputStreamWriter;importjava.net.Socket;importjava.util.HashMap;importjava.util.Map;importcom.alibaba.fastjson.JSON;public classSocketClient {public static voidmain(String[] args) {

InputStreamReader isr;

BufferedReader br;

OutputStreamWriter osw;

BufferedWriter rw;try{

Socket socket= new Socket("IP","端口号");

Map bodyMap= newHashMap();

Map headMap= newHashMap();

headMap.put("报文头", "报文头");

bodyMap.put("报文体", "报文体");

Map sendMap= newHashMap();

sendMap.put("head", headMap);

sendMap.put("body", bodyMap);

ByteArrayOutputStream baos= newByteArrayOutputStream();

String json=JSON.toJSONString(sendMap);

System.out.println("send message:" +json);byte[] content = json.getBytes("UTF-8");

String tmp= ("00000000" +String.valueOf(content.length));

String length= tmp.substring(tmp.length() - 8);

baos.write(length.getBytes());

baos.write(content);try{

writeStream(socket.getOutputStream(), baos.toByteArray());

Object result=readStream(socket.getInputStream());

System.out.println(result);

}catch(Exception e)

{

}finally{if (socket != null) {try{

socket.close();

}catch(IOException e) {

socket= null;

System.out.println("客户端 finally 异常:" +e.getMessage());

}

}

}

}catch(Exception e) {//TODO: handle exception

}

}protected static void writeStream(OutputStream out, byte[] sndBuffer) throwsIOException

{

out.write(sndBuffer);

out.flush();

}protected static Object readStream(InputStream input) throwsException {//TODO Auto-generated method stub

int headLength = 8;byte[] headBuffer = new byte[headLength];for (int offset = 0; offset

}

offset+=length;

}int totalLength = Integer.parseInt(new String(headBuffer, "UTF-8"));byte[] resultBuffer = new byte[totalLength];int offset = 0;while (offset = 0) {

offset+=realLength;

}else{

System.err.println("the length of packet should be :" + totalLength + " but encounter eof at offset:" +offset);throw new RuntimeException("invalid_packet_data");

}

}

String recvStr= new String(resultBuffer, "UTF-8");

System.out.println(recvStr);returnrecvStr.getBytes();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值