Unity3d 分别创建了两个线程客户端 服务器连接的简单示例

//分别创建了两个线程客户端 服务器连接的简单示例 

using UnityEngine;

using System;

using System.Collections;

using System.Threading;

using System.Net.Sockets;

using System.Net;

using System.Text;

public class TCPIPClientServer : MonoBehaviour

{

    void Start()

    {

        Debug.Log(GetIP().ToString());

    }

    public static Socket ClientSocket;

    private void InitConnect()

    {

        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        string ip = GetIP().ToString();//服务器ip

        IPAddress ipa = IPAddress.Parse(ip);

        IPEndPoint iep = new IPEndPoint(ipa, 8000);

        try

        {

            ClientSocket.Connect(iep);//连接到服务器

            Thread thread = new Thread(new ThreadStart(ClientReceive));

            thread.Start();

        }

        catch (Exception ex)

        {

            Debug.Log(ex.Message);

            clientReceiveValue = ex.Message;

        }

    }



    /*接收来自服务器上的信息*/

    public void ClientReceive()

    {

        clientReceiveValue = "已经建立连接准备接受数据";

        while (true)

        {

            byte[] bytes = new byte[100];

            int rev = ClientSocket.Receive(bytes, bytes.Length, 0);//将数据从连接的   Socket   接收到接收缓冲区的特定位置。

            if (rev <= 0)

            {

                break;

            }

            string strev = System.Text.Encoding.Default.GetString(bytes);

            clientReceiveValue = ("服务器对客户端说:" + strev + "\r\n");

        }

    }





    private void ClientSend()

    {

        if (ClientSocket.Connected)//判断Socket是否已连接

        {



            byte[] SendMessage = new byte[100];

            SendMessage = Encoding.ASCII.GetBytes(clientSendValue);

            ClientSocket.Send(SendMessage);//从数据中的指示位置开始将数据发送到连接的Socket。



        }

        else

        {

            Debug.Log("未建立连接!");

            clientSendValue = "未建立连接!";

        }

    }



    private string clientReceiveValue = "";

    private string clientSendValue = "";

    private string serverReceiveValue = "";

    private string serverSendValue = "";

    void OnGUI()

    {

        //服务器

        GUI.TextField(new Rect(100, 100, 200, 50), serverReceiveValue);

        if (GUI.Button(new Rect(310, 100, 100, 20), "开始监听"))

        {

            Listen();

        }

        serverSendValue = GUI.TextField(new Rect(100, 150, 200, 40), serverSendValue);

        if (GUI.Button(new Rect(310, 150, 100, 20), "服务器发送"))

        {

            SeverSend();

        }



        ///客户端

        GUI.TextField(new Rect(100, 350, 200, 40), clientReceiveValue);

        if (GUI.Button(new Rect(310, 350, 100, 20), "连接服务器"))

        {

            InitConnect();



        }



        clientSendValue = GUI.TextField(new Rect(100, 400, 200, 40), clientSendValue);

        if (GUI.Button(new Rect(310, 400, 100, 20), "客户端发送"))

        {

            ClientSend();

        }

    }





    Thread LisThread;

    Socket LisSocket;

    Socket newSocket;

    EndPoint point;

    string strmes = String.Empty;

    int port = 8000;//定义侦听端口号

    private void Listen()

    {

        LisThread = new Thread(new ThreadStart(BeginListern));//开线程执行BeginListern方法

        LisThread.Start();//线程开始执行

        serverReceiveValue = GetIP().ToString() + "正在监听 ";

    }



    private void BeginListern()

    {

        LisSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化Socket

        IPAddress ServerIp = GetIP();/*获取本地服务器的ip地址  */

        IPEndPoint iep = new IPEndPoint(ServerIp, port);



        LisSocket.Bind(iep); /*将Socket绑定ip */

        LisSocket.Listen(50); //Socket开始监听

        newSocket = LisSocket.Accept();//获取连接请求的Socket

        /*接收客户端Socket所发的信息  */

        while (true)

        {

            try

            {



                byte[] byteMessage = new byte[100];

                newSocket.Receive(byteMessage);//接收信息

                point = newSocket.RemoteEndPoint;//获取客户端的Socket的相关信息

                IPEndPoint IPpoint = (IPEndPoint)point;

                strmes += IPpoint.Address.ToString() + "说" + Encoding.Default.GetString(byteMessage).Trim(new char[] { '\0' }) + "\r\n";

                serverReceiveValue = strmes;

            }



            catch (SocketException ex)

            {

                Debug.Log(ex.ToString());

                serverReceiveValue = ex.ToString();

            }

        }

    }



    private IPAddress GetIP()

    {     /*获取本地服务器的ip地址  */

        IPHostEntry iep = Dns.GetHostEntry(Dns.GetHostName());

        IPAddress ip = iep.AddressList[0];

        return ip;

    }



    private void SeverSend()

    {

        byte[] byteData = Encoding.Default.GetBytes(serverSendValue);

        newSocket.Send(byteData);//发送信息即由服务器往客户端上发信息

    }



}

你可能感兴趣的:(Unity3d 分别创建了两个线程客户端 服务器连接的简单示例)