Chinaunix首页 | 论坛 | 博客
  • 博客访问: 23191
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-05 01:34
文章分类

全部博文(1)

文章存档

2015年(1)

我的朋友

分类: Android平台

2015-08-01 12:15:23

欢迎转载!!!但请留下原文链接    
  近期会用到android的tcp通信,于是用qt写了个服务器,客户端在android上运行,写了个测试程序,在此过程中与到的一些问题与大家分享。
     首先是服务器端:qt     源码下载:myservice.zip
   //********************************************************    
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默认编码格式utf8

 clientConnection = 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个字节 (原因还不清楚)

                                   
阅读(2424) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~