Unity Development: UDP network communication between Qt C + + and unity

Source: Internet
Author: User

Try UDP communication again, send faster, more flexible

UDP is actually equivalent to peer communication, without a resume connection, but here in order to have a server concept, the service side bound port, and the client is sent randomly allocated port


Qt C + + service side

Resume GUI project, Pro inside Add Network module, interface put a label, two button

Widget.h

#ifndef widget_h#define widget_h#include <QWidget> #include <qudpsocket>namespace Ui {class WIDGET;} Class Widget:public qwidget{    q_objectpublic:    explicit Widget (Qwidget *parent = 0);    ~widget ();p rivate:    ui::widget *ui;private:    QString statustext;//status information    qudpsocket *udpsocket;//Socket    Qhostaddress ClientIP; Client IP    quint16 clientport;//client Port    void Socketsend (QString sendstr,qhostaddress targetip,quint16 Targetport); Send data that can be sent to the specified target, or broadcast private slots:    void Processpendingdatagram (),///////When receiving data,    void on_leftbtn_clicked ( );    void on_rightbtn_clicked ();}; #endif//Widget_h

Widget.cpp

#include "widget.h" #include "ui_widget.h" Widget::widget (Qwidget *parent): Qwidget (parent), UI (new Ui::widget) {u    I-&GT;SETUPUI (this);    Initialize UDP udpsocket=new qudpsocket (this); Udpsocket->bind (qhostaddress::any,8888);//Bind IP and port, can be any,localhost//label display status statustext=statustext+ "wait for    Connecting ... "+" \ n ";    Ui->statuslabel->settext (statustext); Bind the signal slot to react when the data is received connect (udpsocket,signal (Readyread ()), This,slot (Processpendingdatagram ()));} void Widget::P rocesspendingdatagram () {//waits for data to be received before processing while (Udpsocket->haspendingdatagrams ()) {Qbytear        Ray RecvData;        Recvdata.resize (Udpsocket->pendingdatagramsize ()); Udpsocket->readdatagram (Recvdata.data (), Recvdata.size (), &clientip,&clientport);         Read the data from the sender's package and the IP and port and assign the variable to the class statustext+= "Connet from" +clientip.tostring () + ":" +qstring::number (ClientPort) + "";        Statustext+=recvdata+ "\ n"; Display to Status label Ui->statuslabel->settext (statustext);    Forward back Socketsend ("From server:" +recvdata,clientip,clientport); }}void widget::socketsend (QString sendstr,qhostaddress targetip,quint16 targetport) {Udpsocket->writedatagram ( Sendstr.tostdstring (). C_STR (), Sendstr.length (), targetip,targetport); Widget::~widget () {Delete UI;} Unity object left-handed void widget::on_leftbtn_clicked () {socketsend ("leftrotate", Clientip,clientport);} Unity object Right-handed void widget::on_rightbtn_clicked () {socketsend ("rightrotate", Clientip,clientport);}

Main.cpp not changed, did not post


Unity C # Client

The same thing. The UDP socket part is encapsulated into a class, added to another class, and hung into the scene.

UdpClientHandler.cs

Using unityengine;using system.collections;//using system.net;using system.net.sockets;using System.Text;using System.threading;public class udpclienthandler:monobehaviour{//The following default are private members of the socket socket;//target Socket EndPoint SE Rverend; Service End IPEndPoint Ipend; Server-side port string recvstr; Received string sendstr; Sent string byte[] recvdata=new byte[1024]; The data received must be byte byte[] senddata=new byte[1024]; The data that is sent must be byte int recvlen; The received data length is Thread connectthread; Connection thread//Initialize public void Initsocket () {///define connected server IP and port, can be native IP, LAN, Internet ipend=new IPEndPoint (ipaddr Ess.        Parse ("127.0.0.1"), 8888);        Defines the socket type and defines the socket=new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.DGRAM,PROTOCOLTYPE.UDP) in the main thread;        Define the service-side IPEndPoint sender=new IPEndPoint (ipaddress.any,0);        serverend= (EndPoint) sender;        Print ("Waiting for sending UDP dgram");        To establish the initial connection, it is very important that the first connection is initialized after the serverend to receive the message socketsend ("Hello"); Open a thread connection, must, otherwise the main thread card dies connectthread=new thread (new ThreadStart (socketreceive));    Connectthread.start ();        } public void Socketsend (string sendstr) {//empty send cache senddata=new byte[1024];        Data type conversion senddata=encoding.ascii.getbytes (SENDSTR); Sent to the specified service-side socket.    SendTo (Senddata,senddata.length,socketflags.none,ipend); }//The server receives void Socketreceive () {//Enters receive loop while (true) {//To data clear 0 recv            Data=new byte[1024]; Get the client, get the service end data, assign a value to the server by reference, in fact the server is already defined and does not need to assign a value recvlen=socket.            ReceiveFrom (Recvdata,ref serverend); Print ("Message from:" +serverend.tostring ());            Print Service-side information//output received data recvstr=encoding.ascii.getstring (Recvdata,0,recvlen);        Print (RECVSTR);        }}//Returns the received string, public string Getrecvstr () {string returnstr;        Lock prevents the string from being changed to lock (this) {returnstr=recvstr; } return RETURNSTR; }//Connection off public void Socketquit () {//Close thread if (connectthread!=null) {Connectthre Ad.            Interrupt ();        Connectthread.abort (); }//finally close the socket if (socket!=null) socket.    Close (); }}
UdpTest.cs

Using Unityengine;using system.collections;public class udptest:monobehaviour{string editstring= "Hello wolrd";//edit box    Word gameobject cube;    Udpclienthandler UdpClient; Use of this for initialization void Start () {//Initialize network Udpclient=gameobject.addcomponent<udpclientha        Ndler> ();        Udpclient.initsocket ();    Find Cube Cube=gameobject.find ("Cube"); } void Ongui () {Editstring=gui.        TextField (New Rect (10,10,100,20), editstring); Gui.        Label (New Rect (10,30,300,20), Udpclient.getrecvstr ()); if (GUI.    button (new Rect (10,50,60,20), "send")) Udpclient.socketsend (editstring);            }//update is called once per frame void Update () {if (Udpclient.getrecvstr ()!=null) { Switch (UDPCLIENT.GETRECVSTR ()) {case "leftrotate": Cube.transform.Rotate (Vec                    Tor3.up,50*time.deltatime);                Break             Case "Rightrotate":       Cube.transform.Rotate (Vector3.down,50*time.deltatime);            Break    }}} void Onapplicationquit () {//exit close connection Udpclient.socketquit (); }}

Test

is still the service side and the client to send and receive messages to each other, the server can control the cube rotation inside the client








Unity Development: UDP network communication between Qt C + + and unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.