socket通信里面,如果我变成回忆的c++程序里面有一串整型数组需要传给java程序中,我应该怎么传递比较好呢?

Java服务端
小弟我怎么用socket通信 - Java相关当前位置:& &&&Java服务端
小弟我怎么用socket通信Java服务端
小弟我怎么用socket通信&&网友分享于:&&浏览:0次Java服务端
我如何用socket通信和c++通信时我发送的数据时字符串,c++那边说他只能接收int之类的数据,不能接收字符串的,然后c++发送给我的数据时乱码,求大神告知我Java服务端的代码改如何写------解决思路----------------------socket通讯..&不管是相同语言,&还是不同语言..之间都只能发byte流..
然后客户端和服务器双方,&定义byte流的协议,&就可以了.
字符串也好,&int值也好,&都是可以转换成bytes数组的,&对象就是字符串和数字的结合而已.&所以都可以转换成bytes..
关键的是...socket也只能发送byte.
socket的底层消息是没有所谓的&消息头,&消息内容,&消息长度之类的定义的.&因为对于socket来说,&只是维护了两个缓存流&发送和接收.&发送数据就向流里写,&读取数据就从流里读...&
所以客户端和服务器要自己定义&自己的可用的消息是怎么算的,&比如,&发一个消息.&那发送的一方肯定要告诉&对方,&这个消息有多长,&后面才是消息的具体内容.&这样才能去处理这个消息.
举例,&可以定义前4个字节作为消息的头,&存放消息长度,&后面是消息的内容.
发送"a"这么一个字符串,&那在&前4个字节发送一个&1,&后面再写入&a.&接收的一方,&肯定会先读取到1,&那后面就只需要再读一位,&这样就是一个完整的消息了.
socket里面不会有其他的内容,&所以里面只要有数据,&就肯定是对方发过来的消息,&这样一个一个的去读,&然后解析,&就可以了...
大概就是这样子了吧..------解决思路----------------------定好协议,socket就是能发01010的,看你怎么去组织这些0101了
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有Java Socket通信如何进行通用服务器代码编写,Java教程,Java案例,Java实例
     本站短域名:珠江路.cn、zjlu.net
        
     
       
您的位置: &&
&& Java Socket通信如何进行通用服务器代码编写
Java Socket通信如何进行通用服务器代码编写
Java Socket通信有很多的时候需要我们不断的学习&&。方面效率虽然不及C与C++但它以灵活语言优势,为大家广为使用&&。 本文就对在使用java做通信方面程序时候应改注意问题做以说明&&。
1.长连接、短链接只是针对客户端而言,服务器无所谓长、短;
2.无论同步或者异步通信,发送之后务必要又响应回复,确认收到,负责进行一定范围内重发,例如重发三次;
3.长连接服务器与客户端之间务必需要心跳探测,由客户端主动发起;
4.短连接服务器通用代码:
package&com.biesan.sms. &import&mons.C &import&mons.util.CodeU &import&com.biesan.sms.gate.unioncom.data.*; &import&com.biesan.sms.gate.unioncom.util.GateI &import&java.net.*; &import&java.io.*; &import&java.util.*; &import&org.apache.log4j.*; &import&spApi.*; &public&class&UnioncomDeliver&extends&Thread&{ &//&stop&flag &private&boolean&unInterrupt&=&true; &private&boolean&unErr&=&true; &//private&boolean&closeSocketFlag&=&false; &//&server&socket &private&ServerSocket&serverSo&=&null; &//&current&socket &private&Socket&so&=&null&private&OutputStream&output&=&null; &private&InputStream&input&=&null; &//&gate&command &private&SGIP_Command&tmpCmd&=&null; &private&SGIP_Command&cmd&=&null; &private&Bind&bind&=&null; &private&BindResp&bindResp&=&null; &//private&Unbind&unBind&=&null; &private&UnbindResp&unBindResp&=&null; &private&boolean&unAcceptErrorFlag&=&true; &Logger&unioncomLog&=&Logger.getLogger(UnioncomDeliver.class.getName()); &public&UnioncomDeliver()&{ &} &public&void&run()&{ &<("Start..."); &while&(unInterrupt)&{ &this.initServer(); &this.startServices(); &while&(this.unAcceptErrorFlag)&{ &try&{ &//接受连接请求 &<("before&accept&connection!.......&FreeMemroy&:"&+&Runtime.getRuntime().freeMemory()); &this.acceptConnection(); &<("after&accept&connection!.......&FreeMemroy&:"&+&Runtime.getRuntime().freeMemory()); &while&(unErr)&{ &cmd&=&new&Command(); &<("before&read&command&from&stream...........&FreeMemroy:&"&+&Runtime.getRuntime().freeMemory()); &tmpCmd&=&cmd.read(input); &<("after&read&command&from&stream&"&+&getCommandString(cmd.getCommandID())&+&"&FreeMemroy:&"&+&Runtime.getRuntime().freeMemory()); &if&(tmpCmd&==&null)&{ &unErr&=&false; & &} &switch&(cmd.getCommandID())&{ &//&biad&ready&communication &case&SGIP_Command.ID_SGIP_BIND:&{ &this.dealBind(); & &}//&exit&bind &case&SGIP_Command.ID_SGIP_UNBIND:&{ &this.dealUnBind(); &<("after&unbind&connection!.......&FreeMemroy&:"&+&Runtime.getRuntime().freeMemory()); & &}//&deliver &.... &default&:&//错误的命令字 & &}//&switch &}//&while(unErr) &}&catch&(Exception&e)&{ &unioncomLog.error("Unioncom&Recv&Service&Error" &+&e.getMessage());& &}&finally&{ &if&(this.so&!=&null)&{ &this.closeSocket(); &} &this.unErr&=&true; &} &}//&while&(this.unAcceptErrorFlag) &try&{ &this.closeServerSocket(); &sleep(200);//&sleep &}&catch&(InterruptedException&ie)&{ &} &}//&while(unInterrupt) &} &private&String&getCommandString(int&cmd){ &switch&(cmd)&{ &//&biad&ready&communication &case&SGIP_Command.ID_SGIP_BIND:&{ &return&"&BIND&COMMAND&";& &}//&exit&bind &case&SGIP_Command.ID_SGIP_UNBIND:&{ &return&"&UNBIND&COMMAND&";& &}//&deliver &case&... &default: &return&"&UNKNOWN&COMMAND";& &} &} &private&void&dealBind()&{ &try&{ &bind&=&new&Bind(tmpCmd); &if&(bind.readbody()&!=&0)&{ &unioncomLog.warn("Read&Bind&error"); &this.unErr&=&false; &} &bindResp&=&new&BindResp(tmpCmd.getMsgHead()); &bindResp.SetResult(0); &bindResp.write(output); &unioncomLog.debug("Bind&success!"); &}&catch&(Exception&e)&{ &unioncomLog.error("Dela&Union&Recv&Bind&Error!"&+&e.getMessage()); &this.unErr&=&false; &} &} &private&void&dealUnBind()&{ &try&{ &//unBind&=&(Unbind)&tmpC &unBindResp&=&new&UnbindResp(tmpCmd.getMsgHead()); &unBindResp.write(output); &unioncomLog.debug("UnBind&success!"); &}&catch&(Exception&e)&{ &unioncomLog.warn("Unbind&error!"&+&e.getMessage()); &} &this.unErr&=&false; &} &private&void&startServices()&{ &boolean&unStartServices&=&true; &while&(unStartServices)&{ &try&{ &serverSo&=&new&ServerSocket(ugInfo.getLocalServerPort(),&5, &InetAddress.getByName(ugInfo.getLocalIpAdd())); &//serverSo.setSoTimeout(60000); &unStartServices&=&false;& &<("Create&union&recv&socket&Ok!"); &}&catch&(IOException&e)&{ &unioncomLog.warn("Create&union&recv&socket&error!" &+&e.getMessage()); &unStartServices&=&true; &UnioncomSubmit.thrSlp(3000); &} &} &} &private&void&acceptConnection()&{ &//&Accept&失败 &try&{& &so&=&serverSo.accept(); &so.setSoTimeout(10000); &}&catch&(Exception&e)&{ &unioncomLog.warn("Accept&Error!"&+&e.getMessage()); &this.closeServerSocket(); &this.unAcceptErrorFlag&=&false; &this.unErr=false; &} &//&Accept成功 &try&{ &input&=&so.getInputStream(); &output&=&so.getOutputStream(); &}&catch&(IOException&e)&{ &unioncomLog.warn("Get&I/O&stream&Error!"&+&e.getMessage()); &this.closeService(); &this.unAcceptErrorFlag&=&false; &this.unErr=false; &} &} &private&void&closeSocket()&{ &try&{ &so.close(); &<("Socket&Close&Success!!!"); &}&catch&(Exception&e)&{ &unioncomLog.error("Socket&Close&Failure!!!"&+&e.getMessage()); &} &} &private&void&closeServerSocket()&{ &try&{ &serverSo.close(); &<("ServerSocket&Close&Success!!!"); &}&catch&(Exception&e)&{ &unioncomLog &.error("ServerSocket&Close&Failure!!!"&+&e.getMessage()); &} &} &private&void&closeService()&{ &this.closeSocket(); &this.closeServerSocket(); &} &private&void&initServer()&{ &this.bind&=&null; &this.bindResp&=&null; &//this.unBind&=&null; &this.unBindResp&=&null; &this.tmpCmd&=&null; &this.cmd&=&null; &this.serverSo&=&null; &this.so&=&null; &this.output&=&null; &this.input&=&null; &this.unErr&=&true; &//this.closeSocketFlag&=&false; &<("Memory***===" &+&java.lang.Runtime.getRuntime().freeMemory()); &} &public&synchronized&void&requireStop()&{ &this.unInterrupt&=&false; &<("Requre&interrupt!!!"); &} &public&String&convertMsgContentCoding(int&msgCoding,&byte[]&msgContent)&{ &String&deliverContent&=&null; &try&{ &if&(msgContent&!=&null)&{ &if&(msgCoding&==&8)&{&//&处理ucs32编码 &deliverContent&=&new&String(msgContent, &"UnicodeBigUnmarked"); &}&else&if&(msgCoding&==&0)&{&//&处理ASCII编码 &deliverContent&=&new&String(msgContent,&"ASCII"); &}&else&if&(msgCoding&==&4)&{&//&处理binary编码 &deliverContent&=&new&String(msgContent); &}&else&if&(msgCoding&==&15)&{&//&处理GBK编码 &deliverContent&=&new&String(msgContent,&"GBK"); &//&处理DELIVER数据包的短信息ID &}&else&{ &unioncomLog.error("编码格式错误!"); &return&""; &} &}&else &return&""; &return&deliverC &}&catch&(UnsupportedEncodingException&ex)&{ &unioncomLog.error("deal&content&error!"&+&ex.getMessage()); &return&""; &} &} &}&
以上就是对Java Socket通信的详细介绍&&。希望大家有所帮助&&。
数据库开发
产品库推荐
All Rights Reserved.
珠江路在线版权所有
 |  |  | Java SE &&&&最新内容
Java SE &&&&随机内容在Android上使用LocalSocket实现上层Java和底层C++的通信_Linux编程_Linux公社-Linux系统门户网站
你好,游客
在Android上使用LocalSocket实现上层Java和底层C++的通信
来源:Linux社区&
作者:qwdu
在看代码的时候发现有使用LocalSocket,比java本身的socket效率要高,好像没有经过协议栈,是android自己实现的类似共享内存一样的东东,在传输大量数据的时候就需要用到,比如视频数据,在RIL电话那部分也用到。刚好项目用到视频传输,我试用了一把,果然不错!public static final String SOCKET_ADDRESS = "socket_cmmb_sim_command";//这个名字要记好,在接受端要用到,可以理解为共享内存的设备文件名。.....
&&&&&&&&&&& try {&&&&&&&&&&&&&&& LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS);&&&&&&&&&&&&&&& while (true) {&&&&&&&&&&&&&&&&&&& //Log.i(TAG, "begin accept");&&&&&&&&&&&&&&&&&&& LocalSocket receiver = server.accept();&&&&&&&&&&&&&&&&&&& if (receiver != null) {&&&&&&&&&&&&&&&&&&&&&&& InputStream input = receiver.getInputStream();
&&&&&&&&&&&&&&&&&&&&&&& byte[] bytes = new byte[4];&&&&&&&&&&&&&&&&&&&&&&& int size = input.read(bytes, 0, 4);&&&&&&&&&&&&&&&&&&&&&&& if(size!=4) Log.i(TAG, "received command len:" + String.valueOf(size));
&&&&&&&&&&&&&&&&&&&&&&& int cmd_len = ((bytes[0] & 0xFF) && 24)|((bytes[1] & 0xFF) && 16)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& |((bytes[2] & 0xFF) && 8)|(bytes[3] & 0xFF);
&&&&&&&&&&&&&&&&&&&&&&& Log.i(TAG, "received cmd_len:"+String.valueOf(cmd_len));&&&&&&&&&&&&&&&&&&&&&&& if(cmd_len&0){&&&&&&&&&&&&&&&&&&&&&&&&&&& byte[] ArrayOfByte = new byte[cmd_len];&&&&&&&&&&&&&&&&&&&&&&&&&&& size = input.read(ArrayOfByte, 0, cmd_len);&&&&&&&&&&&&&&&&&&&&&&&&&&& Log.i(TAG, "received data len:" + String.valueOf(size));&&&&&&&&&&&&&&&&&&&&&&&&&&& Parcel parcel = Parcel.obtain();&&&&&&&&&&&&&&&&&&&&&&&&&&& parcel.unmarshall(ArrayOfByte, 0, ArrayOfByte.length);&&&&&&&&&&&&&&&&&&&&&&&&&&& parcel.setDataPosition(0);&&&&&&&&&&&&&&&&&&&&&&&&&&& processRequest(receiver,parcel);&&&&&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&& }&&&&&&&&&&& } catch (IOException e) {&&&&&&&&&&&&&&& Log.e(getClass().getName(), e.getMessage());&&&&&&&&&&& }&&&&&&& private void sendResult(LocalSocket paramLocalSocket, Parcel paramParcel) throws IOException{&&&&&&&&&&& byte[] arrayOfByte1 = new byte[4];&&&&&&&&&&& byte[] arrayOfByte2 = paramParcel.marshall();&&&&&&&&&&& Log.i(TAG, "enter sendResult!");&&&&&&&&&&& arrayOfByte1[0] = 0;&&&&&&&&&&& arrayOfByte1[1] = 0;&&&&&&&&&&& arrayOfByte1[2] = (byte)(arrayOfByte2.length && 8 & 0xFF);&&&&&&&&&&& arrayOfByte1[3] = (byte)(arrayOfByte2.length & 0xFF);
&&&&&&&&&&& paramLocalSocket.getOutputStream().write(arrayOfByte1);&&&&&&&&&&& paramLocalSocket.getOutputStream().write(arrayOfByte2);&&&&&&& }
private void processRequest(LocalSocket paramLocalSocket, Parcel paramParcel){&&&&&&&&& int cmd = paramParcel.readInt();&&&&&&&&& //Log.i(TAG,"parcel:"+String.valueOf(cmd));&&&&&&&&& if(cmd&0&&cmd&CMMB_REQUEST_CMD_MAX){&&&&&&&&& //String info = "unknown";&&&&&&&&& Parcel parcel_info = Parcel.obtain();&&&&&&&&& TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);&&&&&&&&& switch (cmd)&&&&&&&&& {&&&&&&&&& case CMMB_REQUEST_GET_IMSI:{&&&&&&&&&&&&& Log.i(TAG, "received CMMB_REQUEST_GET_IMSI command!");&&&&&&&&&&&&& /*&&&&&&&&&&&&&& * 唯一的用户ID:&&&&&&&&&&&&&& * 例如:IMSI(国际移动用户识别码) for a GSM phone.&&&&&&&&&&&&&& * 需要权限:READ_PHONE_STATE&&&&&&&&&&&&&& */&&&&&&&&&&&&& String info = tm.getSubscriberId();//String&&&&&&&&&&&&& if(info!=null) Log.i(TAG, info);&&&&&&&&&&&&& parcel_info.writeInt(CMMB_REQUEST_GET_IMSI);&&&&&&&&&&&&& parcel_info.writeString(info);&&&&&&&&&&& }&&&&&&&&&&&....&&&&&&&&& try {&&&&&&&&&&&& sendResult(paramLocalSocket, parcel_info);&&&&&&&&& } catch (IOException e) {&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&& Log.e(getClass().getName(), e.getMessage());&&&&&&&&&&& e.printStackTrace();&&&&&&&&& }
以上是服务器端,下面是客户端#define& SOCKET_NAME_CMMB_SIM_COMMAND&& "socket_cmmb_sim_command"...&&& fd = socket_local_client(&&&&&&&&&&&&&&&&&&&&&&&&&&& SOCKET_NAME_CMMB_SIM_COMMAND,&&&&&&&&&&&&&&&&&&&&&&&&&&& ANDROID_SOCKET_NAMESPACE_ABSTRACT,&&&&&&&&&&&&&&&&&&&&&&&&&&& SOCK_STREAM );&&& //check open failed&&& if (fd & 0)&&& {&&&&&&&&&& LOGE("Failed to open socket: %s\n\r'", SOCKET_NAME_CMMB_SIM_COMMAND);&&&&&&&&&&&&&& }
&&& //get command data&&& p_request.writeInt32 (CMMB_REQUEST_GET_IMSI);&&& data = (char *)p_request.data();&&& datasize = (int)p_request.dataSize();&&& //get command length&&& dataLength[0] = dataLength[1] = 0;&&& dataLength[2] = (char)((datasize && 8) & 0xff);&&& dataLength[3] = (char)(datasize & 0xff);
&&& //write command getimsi length&&& if(SmsMbbmsSimSocketWrite(fd, dataLength, sizeof(dataLength)) != sizeof(dataLength))&&& {&&&&&&& LOGE("Failed to write cmmand %d 's length to socket: %s!!!!!\n'", CMMB_REQUEST_GET_IMSI, SOCKET_NAME_CMMB_SIM_COMMAND);&&&&&&&&&& }
&&& //write command getimsi&&& if(SmsMbbmsSimSocketWrite(fd, data, datasize) != datasize)&&& {&&&&&&& LOGE("Failed to write cmmand %d to socket: %s!!!!\n'", CMMB_REQUEST_GET_IMSI, SOCKET_NAME_CMMB_SIM_COMMAND);&&&&&&&&&& }&&& //write end, start read response&&& //read head, include length of data, 4 byte&&& if(SmsMbbmsSimSocketRead(fd, response_data, 4) != 4)&&& {&&&&&&& LOGE("Failed to read response command %d 's length from socket: %s!!!!!\n'", CMMB_REQUEST_GET_IMSI, SOCKET_NAME_CMMB_SIM_COMMAND);&&&&&&&&&& }&&& //LOGD("response_data of length: %d, %d, %d, %d!!!\n", response_data[0], response_data[1], response_data[2], response_data[3]);&&& //calculate length&&& response_length = ((response_data[0] & 0xff) && 24)&&&&&&&&&&&&&&&&&&& | ((response_data[1] & 0xff) && 16)&&&&&&&&&&&&&&&&&&& | ((response_data[2] & 0xff) && 8)&&&&&&&&&&&&&&&&&&& | (response_data[3] & 0xff);&&& //LOGD("response_length = %d\n", response_length);&&& //check length&&& if(response_length == 0)&&& {&&&&&&& LOGE("response %d 's length from socket: %s is not right!!!!!\n'", CMMB_REQUEST_GET_IMSI, SOCKET_NAME_CMMB_SIM_COMMAND);&&&&&&&&&& }...
这样就是实现了客户端和服务器之间的通信。
相关资讯 & & &
& (08/17/:36)
& (08/17/:18)
& (08/17/:43)
& (08/17/:40)
& (08/17/:22)
& (08/16/:38)
图片资讯 & & &
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款Java与C++的Socket通信问题,java socket只接收到4个字符
[问题点数:40分,结帖人kenlaiisme]
Java与C++的Socket通信问题,java socket只接收到4个字符
[问题点数:40分,结帖人kenlaiisme]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。

我要回帖

更多关于 如果我变成回忆 的文章

 

随机推荐