开发者社区> 问答> 正文

java socket客户端和Python socket客户端的不同?

我们接的项目有一个java写的server,我只有它的文档,并且用java已经实现,但是现在要为
python实现,用java实现的代码:

 public static void main(String[] args) throws WindException,   SendException, RecvException{
String host="172.22.128.16";
int port=6001;
TcpComm tcp = new TcpComm(true);
try {
    tcp.call(host,port);
    tcp.setTimeOut(30);
    String msg="POF001|S2B024|01|0033596105||";
    byte[] req = msg.getBytes();
    tcp.sendMsg(req);
    byte[] ans = tcp.recvBytesMsg();
    System.out.println(ans);
} catch (CallException e) {
    e.printStackTrace();
}

接口就是使用socket发送一个定制的代表内容长度的报文头和内容,sendMsg方法:

 public void sendMsg(byte[] b) throws SendException {
        try {
            OutputStream out = sock.getOutputStream();
            if (hasAtrHead) {
                byte[] sbt = short2Byte((short) b.length, true);
                out.write(head);
                out.write(sbt);
            }
            out.write(b);
            out.flush();
        }

其中hasAtrrHead使用的是true,定制报文头的方法:

 static public byte[] short2Byte(short value, boolean order) {
        byte[] bt = new byte[2];
        if (order) { // true 高8位 存放在tb[0]
            bt[0] = (byte) (value >> 8 & 0xff);
            bt[1] = (byte) (value & 0xff);
        } else {
            bt[1] = (byte) (value >> 8 & 0xff);
            bt[0] = (byte) (value & 0xff);
        }
        return bt;
    }

使用以上java代码运行没问题,但是当我用python写的时候,发送的socket没有被server接收到,应该是发送的格式不对,python代码:

 #-*- coding:GBK -*-
import socket
class Comm(object):
    def heads(self,length):
        bt=bytearray()
        bt.append(length >> 8 & 0xff)
        bt.append(length & 0xff)
        return bt
    def client(self):
        HOST='172.22.128.16'
        PORT=6001
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((HOST,PORT))       
        while 1:
            content='POF001|F2B107|01|3061009458||'
            length=len(content)
            head=self.heads(length)
            content=bytearray(content)
            s.send(head)
            s.send(content)
            data=s.recv(2048)    
        s.close()

if __name__=='__main__':
    a=Comm()
    a.client()

有人能告诉我到底是哪里不同吗?

展开
收起
蛮大人123 2016-06-13 11:50:24 4874 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    python中如直接转化数字为byte为4个字节,如需两个字节的网络序byte,需使用struct.pack('!h',x)

    2019-07-17 19:35:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载