62,614
社区成员
发帖
与我相关
我的任务
分享
/**
* 报文头固定5位为报文长度,按长度接收
* @param socket
* @return 接收到的报文
*/
public static byte[] accept(Socket socket){
byte [] head = new byte[5];
byte [] body=null;
try {
BufferedInputStream bufIn = new BufferedInputStream(socket.getInputStream());
bufIn.read(head);
System.out.println("head "+new String(head));
int len1 = Integer.parseInt(new String(head));
body = new byte[len1];
bufIn.read(body);
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
byte[] res = SocketUtil.accept(socket);//读取服务器端返回bytes
String str=new String(res);//转化为String
str=ByteOrStringHelper.ByteToString(res,"GBK");//根据编码格式转化
System.out.println("读取服务器返回数据:"+str);
/**
* 发送报文
*
*/
private Socket socket;
private int msg1_len=100;
private int msg2_len=380;
private String msg1=McisCall.formatString("gd239", msg1_len,0);//
private String msg2=McisCall.formatString("ccc56", msg2_len,0);
MSDate ms=new MSDate("txn121");
public void send() {
try{
socket=new Socket();
socket.connect(new InetSocketAddress("127.0.0.1",8088));
socket.setTcpNoDelay(true);
System.out.println("客户端正在连接...");
byte[] bytes =ms.getDate(msg1+msg2, msg1_len+msg2_len);
String s=new String(bytes);
System.out.println(s+" len "+s.length());
SocketUtil.send(socket, bytes);
System.out.println("发送数据成功");
byte[] res = SocketUtil.accept(socket);//读取服务器端返回bytes
System.out.println("刚读取的:"+res);
String str=new String(res);
System.out.println("Str之后:"+str);
str=ByteOrStringHelper.ByteToString(res,"GBK");
System.out.println("读取服务器返回数据:"+str);
socket.close();
打印00585 txn121 12345677654321 gd239 ccc56 len 585
应该是对的.报文和设计一样.
服务器端就是上面的代码:打印结果为:
txn121 12345677654321 gd239 ccc56 接收到的也是对的.我服务端是直接把接收到的报文返回给客户端的.好像就这里出问题 while(true){
System.out.println("等待客户端连接");
Socket socket=ss.accept();
byte[] rec=SocketUtil.accept(socket);
System.out.println("接受客户端请求成功");
System.out.println("服务器接受到客户端的连接请求:" + new String(rec));// 用于接收客户端 发来的数据的输入流
System.out.println("响应前Length"+rec.length);
SocketUtil.send(socket, rec);//服务器响应给客户端
System.out.println("响应后");
/*
* 启动一个线程去接待它
*/
Thread clientThread = new Thread(new Handler(socket));
clientThread.start();
这是服务端线程循环的,一直响应