发送bytearray时,java和python套接字有什么区别

2024-05-16 08:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个用java编码的服务器,我拿到了api文档,做了一个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();
}
}

我的sendMsg方法是发送一个带有特殊头的bytearray,它表示内容的长度和内容:

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();
        }

我的头方法:

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客户机时,我无法将内容发送到服务器,因为很可能过滤。我的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()

有人能告诉我java客户机和python客户机有什么区别吗?非常感谢!!!你知道吗


Tags: true客户机stringvaluesocketjavacontentbyte