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

Source: Internet
Author: User
Tags server port

Consider implementing the server in C + +, unity does the client to implement TCP network communication.

The following TCP single-threaded connections are used.


Qt C + + service side

Set up a QT GUI project, put a label on the interface to display the connection status, two buttons as instructions to send control.

Remember to include the network module in the Pro file


Widget.h

#ifndef widget_h#define widget_h#include <qwidget>class qtcpserver;//Forward declaration class Qtcpsocket;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    qtcpserver *tcpserver;//Server    Qtcpsocket *clienttcpsocket; Client socket    void Socketsend (QString sendstr);p rivate slots:    void Socketconnet ();    void Socketreceive ();    void on_leftbtn_clicked ();    void on_rightbtn_clicked ();}; #endif//Widget_h
Widget.cpp

#include <QTcpServer> #include <QTcpSocket> #include <QAbstractSocket> #include <qdebug># Include "Widget.h" #include "ui_widget.h" Widget::widget (Qwidget *parent): Qwidget (parent), UI (new Ui::widget) {UI    -&GT;SETUPUI (this); Initialize the server and listen for tcpserver=new qtcpserver (this); QT own memory Management if (!tcpserver->listen (qhostaddress::any,6666))//Listen to all network addresses, Port 6666 qdebug () <<tcpserver->err    Orstring ();    statustext=statustext+ "Wait for connecting ..." + "\ n";    Ui->statuslabel->settext (statustext); Bind the signal slot when there is a connection to react to connect (tcpserver,signal (Newconnection ()), This,slot (Socketconnet ()));}    void Widget::socketconnet () {//Get client Socket clienttcpsocket=tcpserver->nextpendingconnection ();    Bind the signal slots, receive the data, and when the connection is off is delete the connection connect (clienttcpsocket,signal (Readyread ()), This,slot (Socketreceive ()));    Connect (clienttcpsocket,signal (disconnected ()), Clienttcpsocket,slot (Deletelater ())); Display Client connection Information QString CLIENTIP=CLIENTTCPSOCKET-&GT;PEERADDRESS (). toString ();    QString Clientport=qstring::number (Clienttcpsocket->peerport ());    statustext=statustext+ "conneted with" +clientip+ ":" +clientport+ "\ n"; Ui->statuslabel->settext (statustext);} void Widget::socketsend (QString sendstr) {clienttcpsocket->write (Sendstr.tostdstring (). C_STR ());}    void Widget::socketreceive () {//receives data and shows that the byte is converted into a string QString recvstr=clienttcpsocket->readall ();    Statustext=statustext+recvstr+ "\ n";    Ui->statuslabel->settext (statustext); After processing sent back Socketsend ("From server:" +recvstr);} Widget::~widget () {Delete UI;} Send Unity object left-handed message void widget::on_leftbtn_clicked () {socketsend ("leftrotate");} Send Unity object Right-handed message void widget::on_rightbtn_clicked () {socketsend ("rightrotate");}
The main.cpp is not changed and is not posted.


Unity C # Client

Create a unity scene and drag into a cube

The Tcpsocket connection portion is encapsulated into a separate class Tcpclienthandler, and a script tcptest is attached to the scene, where the tcpclienthandler for the connection is instantiated.

TcpClientHandler.cs

Using unityengine;using system.collections;//using system.net;using system.net.sockets;using System.Text;using     System.threading;public class tcpclienthandler:monobehaviour{socket ServerSocket;//server-side socket IPAddress IP;//Host IP    IPEndPoint Ipend; 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 the IP and port of the server, the port corresponds to the server Ip=ipaddress.parse ("127.0.0.1"); To be local area network or Internet IP, here is native ipend=new IPEndPoint (ip,6666);        Server port number//open a thread to connect, must, otherwise the main thread card dies connectthread=new thread (new ThreadStart (socketreceive));    Connectthread.start ();        } void Socketconnet () {if (serversocket!=null) serversocket.close ();        Defines the socket type, which must be defined in the child thread Serversocket=new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);Print ("Ready to connect");        Connection Serversocket.connect (ipend);        Outputs the string recvlen=serversocket.receive (RecvData) received for the initial connection;        Recvstr=encoding.ascii.getstring (Recvdata,0,recvlen);    Print (RECVSTR);        } public void Socketsend (string sendstr) {//empty send cache senddata=new byte[1024];        Data type conversion senddata=encoding.ascii.getbytes (SENDSTR);    Send Serversocket.send (Senddata,senddata.length,socketflags.none);        } void Socketreceive () {socketconnet ();            Continuously receives data from the server while (true) {recvdata=new byte[1024];            Recvlen=serversocket.receive (RecvData);                if (recvlen==0) {socketconnet ();            Continue            } recvstr=encoding.ascii.getstring (Recvdata,0,recvlen);        Print (RECVSTR);        }}//Returns the received string, public string Getrecvstr () {string returnstr;      Lock prevents string from being changed to lock (this)  {returnstr=recvstr;    } return RETURNSTR; } public void Socketquit () {//Close thread if (connectthread!=null) {Connectthread.interrup            T ();        Connectthread.abort ();        }//finally shut down the server if (serversocket!=null) serversocket.close ();    Print ("Diconnect"); }}
TcpTest.cs

Using Unityengine;using system.collections;public class tcptest:monobehaviour{string editstring= "Hello wolrd";//edit box    Word gameobject cube;    Tcpclienthandler tcpClient; Use the this for initialization void Start () {//Initialize network connection//tcpclient=new Tcpclienthandler ();//Because the class relay for TCP Monobehaviour so you can not use new, or remove the inheritance of Monobehaviour to use the new tcpclient=gameobject.addcomponent<tcpclienthandler> ()        ;        Tcpclient.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), Tcpclient.getrecvstr ()); if (GUI.    button (new Rect (10,50,60,20), "send")) Tcpclient.socketsend (editstring);            }//update is called once per frame void Update () {if (Tcpclient.getrecvstr ()!=null) { Switch (TCPCLIENT.GETRECVSTR ()) {case "leftrotate": Cube.transform.RotaTe (vector3.up,50*time.deltatime);                Break                    Case "Rightrotate": Cube.transform.Rotate (Vector3.down,50*time.deltatime);            Break    }}} void Onapplicationquit () {//exit close connection Tcpclient.socketquit (); }}

Test

The program realizes the service side and the client send and receive messages to each other, the service side button can control cube rotation inside the client.






Unity Development: TCP 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.