Reputation: 41
I'm trying to make a Socket connection via TCP protocol.
But my server (written in C++ and running on my PC) does not receive connection request from my client (written in Java and running on Android)
ServerSocket.h (in my PC)
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 (in my PC)
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 (in 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();
}
}
}
}
Could you help me?
Upvotes: 0
Views: 385