Intermediate data transmission

socket connection of unity application - step 2 data transmission

The previous article explained how to use socket to build server and client programs. This article is about socket data transmission.
The purpose of using socket is to solve the data transmission between point-to-point. We mentioned an important concept in socket: port. The way socket transmits data is to stream data between ports. A function class of the stream (NetworkStream) is provided in the socket namespace, which is very convenient to use. Because any data that can be converted into binary can be saved in the stream, any form of data can be transmitted before the client and server.

1. Create a VS console application, create a new c# project in the project, and enter the following code in the script:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("192.168.1.104");
            TcpListener tlistener = new TcpListener(ip, 10001);
            tlistener.Start();//Only when there is a corresponding client, that is, there is the correct ip, can this statement be run
            Console.WriteLine("server Monitor start......");
          
            TcpClient remoteClient = tlistener.AcceptTcpClient();//Connect and return the remoteclient client variable
            Console.WriteLine("client Connected! local:{0}<---Client:{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
            
            //Data sending part of server
            string msg = "hello server";
			//Receive the data of the connected remoteclient, that is, the stream of the client
            NetworkStream streamToClient = remoteClient.GetStream();

            byte[] buffer = Encoding.Unicode.GetBytes(msg);//Convert string to binary

            streamToClient.Write(buffer, 0, buffer.Length);//Write the converted binary data into the stream of the client and send it

            Console.WriteLine("Send message:{0}" , msg);

        }
    }
}

Code analysis:
1.ip address enter ipconfig/all in the cmd command window and press enter to get the local ip address.
2. This is the server, which needs to receive the connection request from the client.
3. The blocking method used here is to wait all the time and continue to output after waiting for the request of the unit client.
4. After connection, the server sends data to the client.

2. The client uses Unity3D. In the unit project, create an empty object in the scene and hang the following script on the object.

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;

public class SocketClient : MonoBehaviour
{
//Request signal to start connection
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            Client();
        }
    }
    
    private void Client()
    {
        TcpClient client = new TcpClient();//client is the variable of the server
        try
        {
            //Establish a TCP connection with the server. After the connection, the client will wait for the data sent by the server
            client.Connect(IPAddress.Parse("192.168.1.104"), 10001);
        }
        catch (Exception ex)
        {
            Debug.Log("Client connection exception:" + ex.Message);
        }
        Debug.Log("LocalEndPoint = " + client.Client.LocalEndPoint + ". RemoteEndPoint = " + client.Client.RemoteEndPoint);


        //The client receives the data sent by the server
        const int bufferSize = 8792;
        NetworkStream streamToClient = client.GetStream();//Get the stream from the server
        byte[] buffer = new byte[bufferSize];//Define a cache buffer array
        int byteRead = streamToClient.Read(buffer, 0, bufferSize);//Store data in cache

        string msg = Encoding.Unicode.GetString(buffer, 0, byteRead);//The client corresponding to converting from binary to string will have the method of converting from string to binary
        Debug.Log("Receive message:" + msg);
    }

   
}

Code analysis:
1. The acquisition of IP address is the same as above, because the connection of the two programs here is on the same computer, so the IP address is the same.
2. When running, first run the first program, and then run the unity program. Enter 1 and 2 in the unity running window, and the first program starts to connect the interface.
Note: the server waits for the client's connection request before connecting.
3. The client receives the data from the server and outputs it.

Successful interface:


1. The amount of data is too large, exceeding the customized cache size, 8192 bytes. Generally, it is almost impossible to send more than 8192 bytes of string. If you send pictures or sound effects, the data will be truncated.

2. The above program is only a process in which the program wants the server to send data once. It cannot be sent multiple times, let alone multiple clients want the server to send data.

Added by dawho9 on Thu, 03 Mar 2022 17:45:13 +0200