Unity online game client (synchronization)

1. Create a Socket

2. Bind the IP address and port number of the server to the Socket

3. Send a message to the server

4. Accept the feedback from the server

using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;

using UnityEngine;
using UnityEngine.UI;

public class Echo : MonoBehaviour
{
    Socket socket;//声明Socket
    public InputField inputF;
    public Text txt;

    public void Connection()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化
        //连接IP和端口号
        socket.Connect("127.0.0.1", 888);//Connect建立与远程主机的连接
    }
    public void Send()
    {
        //发送数据
        string sendStr = inputF.text;
        byte[] sendBuff = System.Text.Encoding.Default.GetBytes(sendStr);
        socket.Send(sendBuff);
        //接收数据
        byte[] res = new byte[1024];
        int count = socket.Receive(res);
        string rsss = System.Text.Encoding.Default.GetString(res,0,count);
        txt.text = rsss;
        socket.Close();
       
    }
}

Guess you like

Origin blog.csdn.net/qq_57388481/article/details/127678053
Recommended