我试图通过TCP协议建立Socket连接。
但我的服务器(用C ++编写,在我的电脑上运行)没有收到客户端的连接请求(用Java编写并在Android上运行)
ServerSocket.h(在我的电脑中)
class ServerSocket: public QObject{
Q_OBJECT
public:
explicit ServerSocket(QObject *rpParent = 0);
void initServerSocket();
public slots:
void acceptConnection();
void startRead();
private:
QTcpServer* server;
QTcpSocket* client;
};
ServerSocket.cpp(在我的电脑中)
ServerSocket::SocketClient(QObject *rpParent) :
QObject(rpParent)
{
server = new QTcpServer(this);
client = new QTcpSocket(this);
}
void ServerSocket::initServerSocket(){
connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
server->listen(QHostAddress::Any, 6005);
while(1){
if(server->hasPendingConnections() ){
printf("hasPendingConnections...\n");
}
}
}
void ServerSocket::acceptConnection(){
client = server->nextPendingConnection();
connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));
}
void ServerSocket::startRead(){
char buffer[1024] = {0};
client->read(buffer, client->bytesAvailable());
printf("startRead %s\n", buffer);
client->close();
}
ClientSocket.java(在Android中)
public class ClientSocket {
private Thread serverThread = null;
public ClientSocket(){
serverThread = new Thread(new ClientThread());
}
public void sendData(){
serverThread.start();
}
class ClientThread implements Runnable {
private PrintWriter printwriter;
public ClientThread() {
}
public void run() {
try {
Socket socket = new Socket("192.168.0.12", 6005);
if( socket.isConnected()){
Log.e("sendData", "connected!");
}
String msg = "Hey server!";
printwriter = new PrintWriter(socket.getOutputStream(), true);
printwriter.write(msg);
printwriter.flush();
printwriter.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
你能帮帮我吗?