Java与C++通信尝试 Socket通信方式

Java与C++复合使用还有其他方式(譬如:JNI的), 今天特地尝试了一种Socket的方式:

本代码展示了,java向C++发送一个Employee的Struct结构; 反向的转化碰到了一些问题:

譬如想将C++发送回来的byte[]转化String,但是不能直接用new String(byte[]), java会忽略掉数组中0(这个零在C++中刚好又是字符串结束的标志)

 

Java端代码(window7, jdk1.6):

Java代码   收藏代码
  1. package tcp.test;  
  2.   
  3. import java.net.*;  
  4.   
  5. /** 
  6.  * 与c语言通信(java做client,c/c++做server,传送一个结构) 
  7.  *  
  8.  * @author kingfish 
  9.  * @version 1.0 
  10.  */  
  11. public class Employee {  
  12.     private byte[] buf = new byte[28]; // 为说明问题,定死大小,事件中可以灵活处理  
  13.   
  14.     /** 
  15.      * 将int转为低字节在前,高字节在后的byte数组 
  16.      */  
  17.     private static byte[] tolh(int n) {  
  18.         byte[] b = new byte[4];  
  19.         b[0] = (byte) (n & 0xff);  
  20.         b[1] = (byte) (n >> 8 & 0xff);  
  21.         b[2] = (byte) (n >> 16 & 0xff);  
  22.         b[3] = (byte) (n >> 24 & 0xff);  
  23.         return b;  
  24.     }  
  25.     /** 
  26.      * 将byte数组转化成String 
  27.      */  
  28.     private static String toStr(byte[] valArr,int maxLen) {  
  29.         int index = 0;  
  30.         while(index < valArr.length && index < maxLen) {  
  31.             if(valArr[index] == 0) {  
  32.                 break;  
  33.             }  
  34.             index++;  
  35.         }  
  36.         byte[] temp = new byte[index];  
  37.         System.arraycopy(valArr, 0, temp, 0, index);  
  38.         return new String(temp);  
  39.     }  
  40.       
  41.     /** 
  42.      * 将低字节在前转为int,高字节在后的byte数组 
  43.      */  
  44.     private static int vtolh(byte[] bArr) {  
  45.         int n = 0;  
  46.         for(int i=0;i<bArr.length&&i<4;i++){  
  47.             int left = i*8;  
  48.             n+= (bArr[i] << left);  
  49.         }  
  50.         return n;  
  51.     }  
  52.     public String name = "";  
  53.     public int id = 0;  
  54.     public float salary = 0;  
  55.     /** 
  56.      * 将float转为低字节在前,高字节在后的byte数组 
  57.      */  
  58.     private static byte[] tolh(float f) {  
  59.         return tolh(Float.floatToRawIntBits(f));  
  60.     }  
  61.       
  62.     private static Employee getEmployee(byte[] bArr) {  
  63.         String name = "";  
  64.         int id = 0;  
  65.         float salary = 0;  
  66.           
  67.         byte[] temp = new byte[20];  
  68.         name = toStr(bArr,20);  
  69.           
  70.         System.arraycopy(bArr, 20, temp, 04);  
  71.         id = vtolh(temp);  
  72.           
  73.         return new Employee(name, id, salary);  
  74.           
  75.   
  76.     }  
  77.     /** 
  78.      * 构造并转换 
  79.      */  
  80.     public Employee(String name, int id, float salary) {  
  81.         this.name = name;  
  82.         this.id = id;  
  83.         this.salary = salary;  
  84.           
  85.         byte[] temp = name.getBytes();  
  86.         System.arraycopy(temp, 0, buf, 0, temp.length);  
  87.   
  88.         temp = tolh(id);  
  89.         System.arraycopy(temp, 0, buf, 20, temp.length);  
  90.   
  91.         temp = tolh(salary);  
  92.         System.arraycopy(temp, 0, buf, 24, temp.length);  
  93.     }  
  94.       
  95.     /** 
  96.      * 返回要发送的数组 
  97.      */  
  98.     public byte[] getbuf() {  
  99.         return buf;  
  100.     }  
  101.   
  102.     /** 
  103.      * 发送测试 
  104.      */  
  105.     public static void main(String[] args) {  
  106.         try {  
  107.             int index = 0;  
  108.             byte[] receive = new byte[28];  
  109.             while(true){  
  110.                 Socket sock = new Socket("127.0.0.1"5050);  
  111.                 System.out.println("send content:  name=kingfish  "+"value="+(1+index));  
  112.                 sock.getOutputStream().write(new Employee("kingfish"+index, 1+index++, 10.99f + index).getbuf());  
  113.                 sock.getInputStream().read(receive);  
  114.                 Employee ee = getEmployee(receive);  
  115.                 System.out.println("    response:  name="+ee.name+"  "+"value="+ee.id);  
  116.                 sock.close();  
  117.             }  
  118.         } catch (Exception e) {  
  119.             e.printStackTrace();  
  120.         }  
  121.     }  
  122. // end   

 

 

C++端代码(环境: window7, visual studio 2008):

 

Cpp代码   收藏代码
  1. // SocketTest.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "stdio.h"     
  6. #include <WINSOCK2.H>    
  7. #pragma comment(lib, "Ws2_32.lib")  
  8.   
  9. struct   UserInfo   {     
  10.   char   UserName[20];     
  11.    int   UserId;     
  12. };     
  13. struct   Employee   {     
  14.   UserInfo   user;     
  15.      float   salary;     
  16. };     
  17. int main(int argc, char* argv[]) {     
  18.   
  19.               WSADATA   wsaData;     
  20.                  char   buf[1024];  
  21.                   int   nBytes=1024, recvbytes;     
  22.                SOCKET   Listening;     
  23.                SOCKET   NewConnection;  
  24.           SOCKADDR_IN   ServerAddr;     
  25.           SOCKADDR_IN   ClientAddr;     
  26.                   int   ClientAddrLen=sizeof(ClientAddr);     
  27.                   int   Port = 5050;     
  28.                   int   c;  
  29.                   WSAStartup(MAKEWORD(2,2),&wsaData);     
  30.                   Listening = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );     
  31.                   ServerAddr.sin_family = AF_INET;     
  32.                   ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);     
  33.                   ServerAddr.sin_port = htons(Port);     
  34.                     
  35.                   bind( Listening, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr) );     
  36.                   listen( Listening, 5 );  
  37.                   printf( "Wating   accpet....\n" );     
  38.   
  39.                    
  40.          while(true) {  
  41.                   NewConnection = accept(Listening,(SOCKADDR   *)&ClientAddr, &ClientAddrLen);     
  42.                   printf( "Wating   recv.....\n" );     
  43.                   if( ( recvbytes=recv(NewConnection,buf,nBytes,0) )   ==   SOCKET_ERROR )     
  44.                   {     
  45.                       printf( "\nErrorcode=%d,   Recv   from   client\n", WSAGetLastError() );  
  46.                       return   0;     
  47.                   }     
  48.                   Employee   *data   =   new   Employee;     
  49.                   data   =   (Employee   *)&buf;     
  50.                       
  51.                   printf( "Userid:   %d   Username:   %s  Salary:  %f", data->user.UserId, data->user.UserName, data->salary );     
  52.                   data->user.UserId = 007;     
  53.                   strcpy(data->user.UserName, "Test");  
  54.                   data->salary = 800;  
  55.                       
  56.                   send( NewConnection, buf, recvbytes, 0 );  
  57.                        
  58.           }  
  59.           return   0;  
  60.   
  61. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值