概述
听说java默认发送是使用UTF8的,而c++默认是gb2312,需要转换一下正确接收
参考资料
http://www.cnblogs.com/kenkofox/archive/2010/04/25/1719649.html
java端发送信息核心代码
头部
private Socket socket=null;
private OutputStream aaa=null;
内容
socket=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++核心代码
// 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++转发过来的数据代码
byte[] 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接收安卓客户端发来信息时乱码的处理所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复