Data communication using sockets in Unity3d (ii)

Source: Internet
Author: User
Tags getstream

The previous blog mainly introduces the use of the socket to build the server and client program, this article says the data transmission of the socket, we use the socket to solve the data transfer between point to point, before referring to an important concept in the socket: port. The way the socket is transmitted is the data transfer between port and port, which provides a functional class (NetworkStream) of the stream, which is very convenient to use. Since any data that can be converted to binary can be saved to the stream, it is possible to transfer any form of data before the client and the server.

Below we introduce the most important transmission data, the client sends the data to the server, and the server receives the data and displays it! It is also customary for the server to use the VS console application. The client uses Unity3d to complete. The core statement has a gaze, and the overloaded method can be viewed on MSDN itself.

If there is any mistake, please correct me!

1. The server receives the data and displays:

static void Main (string[] args) {const int buffersize = 8792;//cache size, 8192 bytes IPAddress IP = IP            Address.parse ("");            TcpListener Tlistener = new TcpListener (IP, 10001); Tlistener.            Start ();            Console.WriteLine ("Server Listener startup ..."); TcpClient remoteclient = Tlistener. AcceptTcpClient ();//Receive connected client, plug method Console.WriteLine ("Client is connected!                       local:{0}<---client:{1} ", RemoteClient.Client.LocalEndPoint, RemoteClient.Client.RemoteEndPoint); Receive the data part of the client sent NetworkStream streamtoclient = Remoteclient.getstream ();//Get stream from client byte[] Bu Ffer = new byte[buffersize];//defines a cache buffer array int byteread = (buffer,0,buffersize);//data into the cache (a friend said that read is a blockage method, the test did not find the program blocked) string msg = Encoding.Unicode.GetString (buffer, 0, byteread);//convert from binary to string the corresponding client will have            Convert from string to binary method Console.WriteLine ("Receive data: {0}[{1}byte]", msg,byteread); ConsOlekey key; do {key = Console.readkey (true).            Key;        } while (Key! = CONSOLEKEY.Q); }

2. The client encapsulates the string and sends:

TcpClient client;    private void Client ()    {        client = new TcpClient ();        Try        {            client. Connect (Ipaddress.parse (""), 10001);//synchronization method, the connection succeeds, throws the exception, the server does not exist and so on before the program will be blocked        }        catch (Exception ex)        {            Debug.Log ("Client connection exception:" +ex. Message);        }        Debug.Log ("Localendpoint =" + client.) Client.localendpoint + ". Remoteendpoint = "+ client." Client.remoteendpoint);        The client sends the data section        string msg = "Hello server";        NetworkStream streamtoserver = client. GetStream ();//Get the client stream        byte[] buffer = Encoding.Unicode.GetBytes (msg);//convert string to binary        streamtoserver.write ( Buffer, 0, buffer. LENGTH);//writes the converted binary data to the stream and sends the        DEBUG.LOG ("Send message:" +msg);}

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

Note: The above is only the basic data communication, there are two problems in the real project:

1, the amount of data is too large than its own definition of cache size, 8192 bytes. It is almost impossible to send a string with more than 8192 bytes, assuming that the data is truncated if the picture or sound is sent.

2, the above procedure is just a process that the program wants to send data to the server. It cannot be sent more than once, and more than one client wants the server to send data.

I went online to check these two questions, should be the corresponding solution. The use of "sub-read, then dump" way to resolve the data volume is too large, using do/while double-layer nesting can solve multiple clients to the server to send multiple messages to the problem. Perhaps will be the plan to share to everyone, with you to learn progress together!

Data communication using sockets in Unity3d (ii)

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: 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.