初学者请教QTcpSocket通信问题,与android通信
请教各位高手一个问题,我想在PC上用Qt做个客户端,与Android上的一个服务端进行通信,不知道用QTcpSocket能不能实现?
我在PC上用QTcpServer做服务端,测试没有问题。在连接Android的服务端的时候就连接失败。
tcpSocket = new QTcpSocket(this);
tcpSocket->connectToHost("127.0.0.1", 19999);
qDebug("State:%d\n",tcpSocket->state());
if(!tcpSocket->waitForConnected(5000))
{
return;
}
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(Error())); //与android连接时就进入这个槽
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
InetAddress serverAddr = null;
serverAddr = InetAddress.getByName("127.0.0.1");
System.out.println("TCP 1111" + "C: Connecting...");
socket = new Socket(serverAddr, port);
String str = "hi,wufenglong";
System.out.println("TCP 221122" + "C:RECEIVE");
BufferedOutputStream out = new BufferedOutputStream(socket
.getOutputStream());
BufferedInputStream in = new BufferedInputStream(socket
.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
boolean flag = true;
while (flag) {
System.out.print("请输入1~6的数字,退出输入exit:");
String strWord = br.readLine();// 从控制台输入1~6
if (strWord.equals("1")) {
out.write("1".getBytes());
out.flush();
System.out.println("1 finish sending the data");
String strFormsocket = readFromSocket(in);
System.out.println("the data sent by server is:/r/n"
+ strFormsocket);
System.out
.println("=============================================");
}
}
tcpSocket = new QTcpSocket(this);
tcpSocket->connectToHost(QHostAddress::LocalHost, 19999);
qDebug("State:%d\n",tcpSocket->state()); //这里是 State:2
if(!tcpSocket->waitForConnected(5000))
{
return;
}
qDebug("State:%d\n",tcpSocket->state()); //这里是 State:3
connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(SocketError_W(QAbstractSocket::SocketError))); //进入这个槽
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(connectionClosedByServer()));
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
void Client::SocketError_W(QAbstractSocket::SocketError)
{
qDebug() << tcpSocket->errorString();
//这里是 "The remote host closed the connection"
}