听说java默认发送是使用UTF8的,而c++默认是gb2312,需要转换一下正确接收
参考资料
http://www.cnblogs.com/kenkofox/archive/2010/04/25/1719649.html
java端发送信息核心代码
头部
复制代码
1
2private Socket socket=null; private OutputStream aaa=null;
内容
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24socket=new Socket(); try{ // socket.connect("192.168.1.100:8888", 2000) socket.connect(new InetSocketAddress("192.168.1.100",8888),2000); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } try { aaa=socket.getOutputStream(); byte[] buffer=new byte[200]; String strbuffer="succeeded!你好"; buffer=strbuffer.getBytes("GB2312"); aaa.write(buffer);
c++核心代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58// SocketTest.cpp : Defines the entry point for the console application. // #include "stdio.h" #include <WINSOCK2.H> #pragma comment(lib, "Ws2_32.lib") struct UserInfo { char UserName[20]; int UserId; }; struct Employee { UserInfo user; float salary; }; int main(int argc, char* argv[]) { WSADATA wsaData; char buf[1024]; int nBytes=1024, recvbytes; SOCKET Listening; SOCKET NewConnection; SOCKADDR_IN ServerAddr; SOCKADDR_IN ClientAddr; int ClientAddrLen=sizeof(ClientAddr); int Port = 8888; WSAStartup(MAKEWORD(2,2),&wsaData); Listening = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); ServerAddr.sin_family = AF_INET; ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); ServerAddr.sin_port = htons(Port); bind( Listening, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr) ); listen( Listening, 5 ); printf( "Wating accpet....n" ); while(true) { NewConnection = accept(Listening,(SOCKADDR *)&ClientAddr, &ClientAddrLen); printf( "Wating recv.....n" ); if( ( recvbytes=recv(NewConnection,buf,nBytes,0) ) == SOCKET_ERROR ) { printf( "nErrorcode=%d, Recv from clientn", WSAGetLastError() ); return 0; } Employee *data = new Employee; data = (Employee *)&buf; printf( "Userid: %d Username: %s Salary: %f", data->user.UserId, data->user.UserName, data->salary ); data->user.UserId = 007; strcpy(data->user.UserName, "Test郑海波"); data->salary = 800; send( NewConnection, "aaa", recvbytes, 0 ); } return 0; }
安卓客户端接收c++转发过来的数据代码
复制代码
1
2
3
4
5byte[] buf = new byte[1024]; int len = in.read(buf); //String text1 = new String(buf,0,len); String text1 = new String(buf,"GB2312").trim(); text.setText(text1);
最后
以上就是仁爱戒指最近收集整理的关于c++服务器通过socket接收安卓客户端发来信息时乱码的处理的全部内容,更多相关c++服务器通过socket接收安卓客户端发来信息时乱码内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复