Unity uses UDP protocol for interconnection between local server and client

Unity uses UDP protocol for interconnection between local server and client

Previous tip:
When we use Unity to develop, we will inevitably encounter interactions between two hosts or multiple hosts (for example: when developing a double egg chair, in order to allow the two hosts in the egg chair to communicate with each other), and Remotely control the computer to shut down. Without further ado, I will give you the code directly. Dear brothers, sisters, younger brothers and sisters, please forgive me for any shortcomings.

Service-Terminal:

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.IO;
public class UDPServer : MonoBehaviour
{
public string ipAddress = “192.168.28.58”;
public int ConnectPort = 7401;
public string recvStr;
Socket socket;
EndPoint clientEnd;
IPEndPoint ipEnd;
string sendStr;
byte[] recvData = new byte[1024];
byte[] sendData = new byte[1024];
int recvLen;
Thread connectThread;
//判断服务器是否跳转场景
bool isJumpScene = false;
//IP address
string ip;
//Initialization
void InitSocket()
{ ipEnd = new IPEndPoint(IPAddress.Parse(ipAddress), ConnectPort); socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType. Udp); socket.Bind(ipEnd); //Define client IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); clientEnd = (EndPoint)sender; print("Waiting for connection data"); //Open a thread connection connectThread = new Thread(new ThreadStart(SocketReceive)); connectThread.Star









Guess you like

Origin blog.csdn.net/g947195395/article/details/112977762