繁体   English   中英

Java套接字到C套接字

[英]Java sockets to C sockets

谁能帮助我将此Java代码转换为C。我尝试了许多不同的方法,但没有成功。 我在缓冲区部分遇到了问题,我不知道如何存储数据,然后使用C套接字发送数据。

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 6633));

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

byte version = 0x01;
short length = 8;
byte type = 0;

buf.put(version);
buf.put(type);
buf.putShort(length);
buf.putInt(12356);

buf.flip();
socketChannel.write(buf);

谢谢。

下面是代码:

SOCKET sock = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in thataddr;
thataddr.sin_addr.s_addr = inet_addr("127.0.0.1");
thataddr.sin_family = AF_INET;
thataddr.sin_port = htons(6633);
connect(sock, (LPSOCKADDR) &thataddr, sizeof(thataddr));
typedef struct SendThis    
{
    unsigned char version;
    unsigned int length;
    unsigned char type;
};
SendThis sendThis;
sendThis.version = '1';
sendThis.length = 8;
sendThis.type = 0;
send(sock,(char *)&sendThis,sizeof(SendThis),0);

它未经测试,也可以在需要的地方添加错误检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM