分类: Android平台
2015-08-01 12:15:23
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);//创建tcpserver
if(!tcpServer->listen(QHostAddress("192.168.0.116"),6666)){
qDebug()<<tcpServer->errorString();//监听本机ip 端口 6666
close();
}
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));//若有连接,则发出newConnection信号,执行sendMessage()槽函数。
}
//************************************************************
void MainWindow::sendMessage(){QByteArray block;QDataStream out(&block,QIODevice::WriteOnly); //以数据流的形式发送数据out<<QString("hello tcp\r\n").toUtf8();//android tcp默认编码格式utf8clientConnection = tcpServer->nextPendingConnection();//得到建立的连接connect(clientConnection,SIGNAL(disconnected()),clientConnection,SLOT(deleteLater()));//connect(clientConnection,SIGNAL(readyRead()),this,SLOT(readMessage()));//将数据来到时发送的信号与接收数据槽函数连接clientConnection->setSocketOption(QAbstractSocket::LowDelayOption,"1");clientConnection->write(block);//写入数据clientConnection->flush();//刷新ui->textBrowser->setText("send message successfull");//提示已有连接}
//****************************************************************
void MainWindow::readMessage() { qDebug()<<"read message"; QString message=NULL; quint16 blockSize=0; if(clientConnection->bytesAvailable()>0)//如果收到数据数量大于0 { QByteArray datagram; datagram.resize(clientConnection->bytesAvailable());//得到数据量 clientConnection->read(datagram.data(),datagram.size());//读取数据到datagram QString message=datagram.data(); qDebug()<textBrowser->append(message);//以追加形式显示 } }
客户端:android 源码下载:tcpclient.zip protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); new Thread(networkTask).start();//以线程形式访问网络 4.0以上 }//******************************************************* Runnable networkTask = new Runnable() { @Override public void run() { // TODO Auto-generated method stub //net try{ Socket socket1 = new Socket("192.168.0.116",6666);//创建连接电脑服务器 br = new BufferedReader( new InputStreamReader(socket1.getInputStream(),"utf-8"));//读 InputStream utf8 recv = new BufferedWriter( new OutputStreamWriter(socket1.getOutputStream(),"utf-8")); //写 OutputStream utf8 send = (Button)findViewById(R.id.button1);//发送按钮 send.setOnClickListener(new OnClickListener() {//监听点击事件 public void onClick(View arg0) { // TODO Auto-generated method stub String line = null; EditText show; show = (EditText)findViewById(R.id.editText1); line = show.getText().toString(); //获得发送数据 Log.v("sned ...", line); try { recv.write(line);//往输出流写入数据 recv.flush();//刷新 Log.v("send WRITE", "WRITE OVER"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); String line=null; while(true){ try{ line = br.readLine(); //读取一行 } catch(IOException e) { socket1.close(); } line = line.substring(4);//去掉头4个字节 Log.v("this socket","recv="+line); //br.close(); //socket1.close(); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value",line); msg.setData(data); handler.sendMessage(msg);//在handler处理显示数据 } }catch(IOException e){ e.printStackTrace(); } } };
//***************************************************************************
Handler handler = new Handler(){ public void handleMessage(Message msg){ super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Log.v("handler","data:"+val); //UI EditText show; show = (EditText)findViewById(R.id.editText1); show.setText(val.toCharArray(),0,val.length()); } };
//********************************************************
实现功能:
客户端连接服务器,服务器发送欢迎连接字符串给客户端,然后客户端可以发送数据给服务器端。
//************************************************************
问题:
1,服务器端qt程序发送数据给android,必须等待qt程序关闭才能收到数据。
解决: 客户端使用readLine读取一行数据,数据末尾需加"\r\n".
2, 通信数据乱码
解决:使用相同的编码方式 utf-8
3,qt发给android数据前几个数据显示为空
解决: line = line.substring(4);//去掉头4个字节 (原因还不清楚)