聊天-qt 用UDP广播后,无法接受到广播的内容怎么回事,求指教。

图片 1

由于本人没有无线路由器,因此用Win7自带的虚拟wifi让手机上网:

qt编程:windows下的udp通信

qt 用UDP广播后,无法接受到广播的内容怎么回事,求指教。
#include “mainwindow.h”
#include “ui_mainwindow.h”
int port = 8888;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow,
ui(new Ui::MainWindow)
{
ui->setupUi;

但是,电脑不在我的房间,因此每天晚上在床上玩完手机还要下床去关电脑,让很懒很懒的本人很不爽,因此自己尝试着做了一个远程控制。

 

}

软件客户端运行在Android设备上,服务器端运行在我的Win7本本上。客户端用的是Android平台应用编程,服务器端用的是Qt编写的。

本文博客链接:,作者:jdh,转载请注明.

MainWindow::~MainWindow()
{
delete ui;
}

首先设置好默认端口,然后设置控制方法,为了方便起见,这里直接利用标准C中的system接口。客户端发送命令给服务器,服务器直接执行命令,并将标准输出返回给客户端。

 

void MainWindow::recvmydata()//接收数据
{
//char buf[1024]={0};
while(udpSocket->hasPendingDatagrams
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize;
udpSocket->readDatagram(datagram.data(),datagram.size;

下面看一些代码,具体代码可以到这里下载:

环境:

 // udpSocket->readDatagram(buf,sizeof; ui->textBrowser->append(datagram.data; //memset(buf,0,sizeof; }

服务器端:

主机:win7

}
void MainWindow::mysenddata()//发送数据
{
QString ip = ui->ip_lineEdit->text();
QString name = ui->name_lineEdit->text();
QString txt=ui->plainTextEdit->toPlainText();
char buf[1024]={0};
strcpy(buf,txt.toStdString;
//QHostAddress::Broadcast *serip=new QHostAddress::Broadcast();
//serip->Q(“192.168.23.255”);
//udpSocket->writeDatagram(txt,txt.length(),QHostAddress::Broadcast,8888);
udpSocket->writeDatagram(buf,strlen,QHostAddress::Broadcast, 8888);
//delete serip;
ui->plainTextEdit->clear();

头文件:

开发环境:qt

}

mainwindow.h

 

void MainWindow::on_pushButton_2_clicked()
{
QString ip = ui->ip_lineEdit->text();
QString name = ui->name_lineEdit->text();
if(ip.isEmpty{
QMessageBox::information(this,”请输入IP地址”,”IP地址不能为空!”);
}else if (name.isEmpty{
QMessageBox::information(this,”请输入名字”,”名字不能为空!”);
}else if(ip.isEmpty() && name.isEmpty{
QMessageBox::information(this,”请输入名字和IP”,”名字和不能为空!”);
}else{
QMessageBox::information(this,”欢迎加入聊天室”,”欢迎”+name+”加入聊天室”);
udpSocket = new QUdpSocket;
udpSocket->bind(8888,QUdpSocket::ShareAddress |
QUdpSocket::ReuseAddressHint);
connect(udpSocket,SIGNAL(readyRead,this,SLOT(recvmydata;
connect(ui->pushButton,SIGNAL),this,SLOT(mysenddata;
}
}

#ifndef MAINWINDOW_H

功能:

为要写一个聊天室UDP的

#define MAINWINDOW_H

用udp进行收发通信

#include QMainWindow

 

#include QtNetwork/QTcpServer

界面:

#include QTextDocument

图片 1

#include server.h

 

namespaceUi {

源代码:

classMainWindow;

LssHost.pro:

}

 

classMainWindow :publicQMainWindow

[cpp] view
plain copy

{

 

Q_OBJECT

  1. #————————————————-  
  2. #  
  3. # Project created by QtCreator 2013-09-22T09:36:44  
  4. #  
  5. #————————————————-  
  6.   
  7. QT       += core gui  
  8. QT       += network  
  9.   
  10. TARGET = LssHost  
  11. TEMPLATE = app  
  12.   
  13.   
  14. SOURCES += main.cpp  
  15.         mainwindow.cpp  
  16.   
  17. HEADERS  += mainwindow.h  
  18.   
  19. FORMS    += mainwindow.ui  

public:

mainwindows.h

explicitMainWindow(QWidget *parent = 0);

 

QTextDocument *textDocument;

 

Server *server;

[cpp] view
plain copy

~MainWindow();

 

publicslots:

  1. #ifndef MAINWINDOW_H  
  2. #define MAINWINDOW_H  
  3.   
  4. #include <QMainWindow>  
  5. #include <QtNetwork/QUdpSocket>  
  6.   
  7. namespace Ui {  
  8.     class MainWindow;  
  9. }  
  10.   
  11. class MainWindow : public QMainWindow  
  12. {  
  13.     Q_OBJECT  
  14.   
  15. public:  
  16.     explicit MainWindow(QWidget *parent = 0);  
  17.     ~MainWindow();  
  18.   
  19. private:  
  20.     Ui::MainWindow *ui;  
  21.   
  22.     QUdpSocket *udp_socket_tx;  
  23.     QUdpSocket *udp_socket_rx;  
  24.     QHostAddress Ip_Tx;  
  25.     int Port_Tx;  
  26.   
  27. private slots:  
  28.     void on_btn_cfg_clicked();  
  29.     void on_btn_tx_clicked();  
  30.     void rx_udp();  
  31. };  
  32.   
  33. #endif // MAINWINDOW_H  

voidgetConnect();

mainwindows.cpp:

voidexecCommand(constchar*command,intlength,constchar*add,intclientCode);

 

voidshowText(constchar*text);

 

signals:

[cpp] view
plain copy

voidwriteFile(intclientCode);

 

private:

  1. #include “mainwindow.h”  
  2. #include “ui_mainwindow.h”  
  3.   
  4. MainWindow::MainWindow(QWidget *parent) :  
  5.     QMainWindow(parent),  
  6.     ui(new Ui::MainWindow)  
  7. {     
  8.     ui->setupUi(this);  
  9.   
  10.     udp_socket_tx = new QUdpSocket(this);  
  11.     udp_socket_rx = new QUdpSocket(this);  
  12.   
  13.     ui->btn_tx->setEnabled(false);  
  14. }  
  15.   
  16. MainWindow::~MainWindow()  
  17. {  
  18.     delete ui;  
  19. }   
  20.   
  21. //接收udp数据  
  22. void MainWindow::rx_udp()  
  23. {  
  24.     qDebug() << “rx”;  
  25.   
  26.     while (udp_socket_rx->hasPendingDatagrams())  
  27.     {  
  28.              QByteArray datagram;  
  29.              datagram.resize(udp_socket_rx->pendingDatagramSize());  
  30.   
  31.              QHostAddress sender;  
  32.              quint16 senderPort;  
  33.   
  34.              udp_socket_rx->readDatagram(datagram.data(), datagram.size(),  
  35.                                      &sender, &senderPort);  
  36.   
  37.              ui->txt_rx->append(datagram);  
  38.          }  
  39. }  
  40.   
  41. //发送按键  
  42. void MainWindow::on_btn_tx_clicked()  
  43. {  
  44.     QByteArray datagram = ui->txt_tx->toPlainText().toAscii();  
  45.     udp_socket_tx->writeDatagram(datagram, datagram.size(), Ip_Tx, Port_Tx);  
  46. }  
  47.   
  48. //配置按键  
  49. void MainWindow::on_btn_cfg_clicked()  
  50. {  
  51.     bool ok;  
  52.     int port_rx = 0;  
  53.   
  54.     //获得发送IP和端口  
  55.     Ip_Tx = QHostAddress(ui->txt_ip->text());  
  56.     Port_Tx = ui->txt_port_tx->text().toInt(&ok);  
  57.     //获得接收端口  
  58.     port_rx = ui->txt_port_rx->text().toInt(&ok);  
  59.     udp_socket_rx->bind(QHostAddress::Any, port_rx);  
  60.   
  61.     //绑定接收信号槽  
  62.     connect(udp_socket_rx, SIGNAL(readyRead()),this, SLOT(rx_udp()));  
  63.   
  64.     ui->btn_tx->setEnabled(true);  
  65. }  

Ui::MainWindow *ui;

main.cpp:

};

 

#endif // MAINWINDOW_H

 

server.h

[cpp] view
plain copy

#ifndef SERVER_H

 

#define SERVER_H

  1. #include <QtGui/QApplication>  
  2. #include “mainwindow.h”  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QApplication a(argc, argv);  
  7.     MainWindow w;  
  8.     w.show();  
  9.   
  10.     return a.exec();  
  11. }  

#include QTextDocument

#include QTcpServer

classMainWindow;

classServer:publicQTcpServer

{

Q_OBJECT

private:

intport;

MainWindow *mainWindow;

QHostAddress hostAddress;

intclientNum;//已建立的客户端连接数

public:

Server(MainWindow *m,intp,QHostAddress a);

voidincomingConnection(inthandle);

signals:

voidprintText(constchar*text);

};

#endif // SERVER_H

serverthread.h

#ifndef SERVERTHREAD_H

#define SERVERTHREAD_H

#include QThread

#include QTcpSocket

#include mainwindow.h

classServerThread:publicQThread

{

Q_OBJECT

private:

QTcpSocket *socket;

MainWindow *mainWindow;

intclientCode;

public:

ServerThread(intsocketDescriptor,QObject *parent,MainWindow
*m,intclientCode);

voidrun();

signals:

voidnewCommand(constchar*str,constintlength,constchar*add,intclientCode);

publicslots:

voidreceiveData();

voidreadFile(intcC);

};

#endif // SERVERTHREAD_H

源代码:

main.cpp

#include QtGui/QApplication

#include mainwindow.h

intmain(intargc,char*argv[])

{

QApplication a(argc, argv);

MainWindow w;

w.show();

returna.exec();

}

mainwindow.cpp

#include QtNetwork/QHostAddress

#include QTextDocument

#include string

#include cstring

#include string.h

#include mainwindow.h

#include ui_mainwindow.h

MainWindow::MainWindow(QWidget *parent) :

QMainWindow(parent),

ui(newUi::MainWindow)

{

ui-setupUi(this);

server=newServer(this,5648,QHostAddress::Any);//初始化服务器

}

MainWindow::~MainWindow()

{

deleteui;

}

voidMainWindow::getConnect()

{

QTextDocument *textDocumentM=newQTextDocument(QString(new connect
!),this);

ui-textEdit-setDocument(textDocumentM);

server-nextPendingConnection();

}

voidMainWindow::execCommand(constchar*command,intlength,constchar*add,intclientCode)

{

QTextDocument *textDocumentC=newQTextDocument(QString(message),this);

char*commandStr=newchar[length+15];

strcpy(commandStr,command);

char*para=commandStr+length;

char*c= temp.txt;//将结果重定向到一个临时文件

strcpy(para,c);

system(commandStr);//执行shell命令

emit writeFile(clientCode);

ui-textEdit-setDocument(textDocumentC);

}

voidMainWindow::showText(constchar*text)

{

QTextDocument *textDocumentT=newQTextDocument(QString(text),this);

ui-textEdit-setDocument(textDocumentT);

}

server.cpp

#include server.h

#include serverthread.h

Server::Server(MainWindow *m,intp,QHostAddress a)

{

this-hostAddress=a;

this-port=p;

this-mainWindow=m;

this-clientNum=0;//初始化客户连接数

this-QTcpServer::listen(hostAddress,quint16(port));

connect(this,SIGNAL(printText(constchar*)),this-mainWindow,SLOT(showText(constchar*)));

}

voidServer::incomingConnection(inthandle)

{

charch[]=new connection !;

emit printText(ch);

ServerThread
*thread=newServerThread(handle,this,mainWindow,this-clientNum);//每建立一个连接,都会开启一个服务线程,线程有客户编号

this-clientNum++;

thread-start();

}

serverthread.cpp

#include serverthread.h

#include QFile

#define COMMAND_SIZE 50

ServerThread::ServerThread(intsocketDescriptor,QObject
*parent,MainWindow *m,intc):QThread(parent)

{

this-mainWindow=m;

this-clientCode=c;

socket=newQTcpSocket(parent);

socket-setSocketDescriptor(socketDescriptor);

}

voidServerThread::run()

{

this-connect(socket,SIGNAL(readyRead()),this,SLOT(receiveData()));

connect(this,SIGNAL(newCommand(constchar*,int,constchar*,int)),this-mainWindow,SLOT(execCommand(constchar*,int,constchar*,int)));

connect(this-mainWindow,SIGNAL(writeFile(int)),this,SLOT(readFile(int)));

exec();

}

voidServerThread::receiveData()

{

intleft=socket-bytesAvailable();

char*command=newchar[COMMAND_SIZE];

while(left0)

{

intread=socket-readLine(command,COMMAND_SIZE);//读取原始命令

emit newCommand(command,read,test,this-clientCode);

left-=read;

}

}

//读取临时文件中的标准输出信息并写入socket传回给客户端

voidServerThread::readFile(intcC)

{

if(cC==this-clientCode)

{

QFile *file=newQFile(temp.txt);

if(file-open(QIODevice::ReadWrite))

{

char*buffer=newchar[100];

intlength;

while((length=file-read(buffer,100))0)

{

socket-write(buffer,length);

}

}

socket-flush();

file-close();

system(del temp.txt);//删除临时文件

}

}

客户端:

只有一个Acitvity

MainActivity.java

packagecom.tobacco.phonetest;

importjava.io.BufferedReader;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

importjava.net.Socket;

importjava.net.UnknownHostException;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.os.Handler;

importandroid.util.Log;

importandroid.view.Menu;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

importandroid.widget.EditText;

importandroid.widget.TextView;

publicclassMainActivityextendsActivityimplementsOnClickListener,Runnable{

privateButton button;

privateButton clear;

privateEditText editText;

privateTextView tv;

privateSocket socket;

privatePrintWriter pw;

privateBufferedReader br;

//private InputStream is;

privateHandler handler;

@Override

publicvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

handler=newHandler();

button=(Button)findViewById(R.id.button);

clear=(Button)findViewById(R.id.clear);

button.setOnClickListener(this);

clear.setOnClickListener(this);

editText=(EditText)findViewById(R.id.edittext);

tv=(TextView)findViewById(R.id.textView);

try{

//socket=new Socket(tobacco5648.xicp.net,5648); //我的pc域名

socket=newSocket(192.168.137.1,5648);//建立socket,这里应该根据pc的ip地址进行修改

//socket=new Socket(,80);

}catch(UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

Log.e(socket,unknown host);

}catch(IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

Log.e(socket,io execption);

}

if(socket==null){

Log.e(socket,null);

}

else

try{

pw=newPrintWriter(socket.getOutputStream());

br=newBufferedReader(newInputStreamReader(socket.getInputStream(),gbk));

String remote=socket.getInetAddress().getHostAddress();

String self=socket.getLocalAddress().getHostAddress();

tv.setText(connected!+rn+remote:+remote+rn+local:+self+rn);

//is=socket.getInputStream();

if(pw!=nullbr!=null){

newThread(this).start();

}

}catch(IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

@Override

publicbooleanonCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.activity_main, menu);

returntrue;

}

publicvoidonClick(View view) {

if(view==button){

String str;

str=editText.getText().toString();

pw.print(str);

pw.flush();

}

elseif(clear==view){

tv.setText();

}

}

publicvoidrun() {

while(true){

try{

String str;

while((str=br.readLine())!=null){

finalString s=str;

handler.post(newRunnable(){

publicvoidrun() {

tv.setText(tv.getText()+s+rn);

}});

}

}catch(IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图