2014-01-24 210 views
1

任何人都可以幫助我把這個Java代碼翻譯成C.我嘗試了很多不同的方式,但沒有成功。我在緩衝區部分存在問題,我不知道如何存儲數據,然後使用C套接字發送它。Java套接字到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); 

謝謝。

+0

這是類似於你要找的東西:http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_15.html –

回答

2

下面是代碼:

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

它不是測試,還添加錯誤檢查,任何需要的地方。