socket C#服务端和QT客户端通信

(1) C#服务端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Net.Sockets;
using System.Net;  

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        private static byte[] result = new byte[1024];
        private static int myProt = 8885;   //端口
        static Socket serverSocket;  

        public Form1()


        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
                Thread.Sleep(1000);
                break;
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }  

    }
}


(2) QT的C++代码

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    mp_clsTcpSocket = new QTcpSocket();

       mp_clsTcpSocket->connectToHost("127.0.0.1",8885);

       connect(mp_clsTcpSocket,SIGNAL(readyRead()),this, SLOT(slot_readmesg()));

       if (mp_clsTcpSocket->waitForConnected(1000))
       {
           qDebug() << "connect success !";

       }else{

           qDebug() << "connect faild !";

       }

}

void Widget::slot_WritMsgToServer(QString str)
{
    mp_clsTcpSocket->write(str.toLatin1());
}

void Widget::slot_readmesg()
{

    QByteArray buffer = mp_clsTcpSocket->readAll();

    qDebug() <<"msg:"<< buffer;

}

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

void Widget::on_pushButton_clicked()
{
    QString str = "111";
    mp_clsTcpSocket->write(str.toLatin1());
}


(3)要先启动C#服务端代码。

猜你喜欢

转载自blog.csdn.net/qq_14874791/article/details/109332993