我正在尝试通过 TCP 协议建立 Socket 连接。
但是我的服务器(用 C++ 编写并在我的 PC 上运行)没有收到来自我的客户端的连接请求(用 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();
}
}
}
}
你可以帮帮我吗?