简单的unity 客户端与服务端互相发送消息

来源:互联网 发布:淘宝达人头像要求 编辑:程序博客网 时间:2024/06/07 10:13

服务器部分用C#写的

首先是 游戏client

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Collections;namespace wsocketbydx{    class GameClient    {        public static Hashtable allClient = new Hashtable();           public static List<string> ipList = new List<string>();        private TcpClient _client;        public string _clientIP;        public string _clientNick;        private byte[] data;                public GameClient(TcpClient client)        {            this._client = client;            this._clientIP = client.Client.RemoteEndPoint.ToString();            if (allClient.Count <= 2)            {                allClient.Add(this._clientIP, this);                ipList.Add(this._clientIP);                data = new byte[this._client.ReceiveBufferSize];                client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), RceiveMessage, null);                this.sendMessage("login success");            }            else            {                this.sendMessage("connect num is max,so connect failed");            }        }        public void RceiveMessage(IAsyncResult ar)        {            int bytesread;            try            {                lock (this._client.GetStream())                {                    bytesread = this._client.GetStream().EndRead(ar);                }                if (bytesread < 1)                {                    allClient.Remove(this._clientIP);                    Guangbo("server error");                    return;                }                else                {                    string messageReceived = System.Text.Encoding.UTF8.GetString(data, 0, bytesread);                    Console.WriteLine("server recive :" + messageReceived);                    if (!messageReceived.Contains("+"))                    {                        this._clientNick = messageReceived;                        Console.WriteLine(this._clientIP + this._clientNick);                    }                    else                    {                        string[] strVect = messageReceived.Split('+');                    }                    lock (this._client.GetStream())                    {                        this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize),                            RceiveMessage, null);                    }                }            }            catch (Exception ex)            {                Console.WriteLine("something wrong");                allClient.Remove(this._clientIP);                Guangbo(this._clientNick + " leave");            }        }        public void Guangbo(string message)        {            foreach (DictionaryEntry c in allClient)            {                ((GameClient)(c.Value)).sendMessage(message);            }        }        public void sendMessage(string message)        {            Console.WriteLine("server" + this._clientNick + " send " + message);            try            {                System.Net.Sockets.NetworkStream ns;                lock (this._client.GetStream())                {                    ns = this._client.GetStream();                }                byte[] bytestosend = System.Text.Encoding.UTF8.GetBytes(message);                ns.Write(bytestosend, 0, bytestosend.Length);                ns.Flush();            }            catch (Exception ex)            {            }        }    }}

接受到消息字符串之后 可以自行切割处理



服务端启动

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;namespace wsocketbydx{    class Program    {        const int porNo = 500;        static void Main(string[] args)        {            System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");  //本地ip            TcpListener listener = new TcpListener(localAdd, porNo); //端口号            listener.Start();   //开启监听            Console.WriteLine("server is running");            int i = 1;            while (true)            {                GameClient user = new GameClient(listener.AcceptTcpClient());                Console.WriteLine(user._clientIP + "   client logined");            }        }    }}

运行效果




接下来是unity 客户端

建立了一个 client脚本

using UnityEngine;using System.Collections;using System;using System.Text;using System.Net.Sockets;using System.Threading;using System.Collections.Generic;using System.ComponentModel;using UnityEngine.UI;public class Socket : MonoBehaviour {    public static Socket instance;    public int portNo = 500;    private TcpClient _client;    byte[] data;    public string url = "127.0.0.1";    public void Awake()    {        instance = this;    }    public string idtext="";    bool connect = false;  //只允许登录一次    public void login()    {        if (idtext != ""&& !connect)        {            connect = true;            this._client = new TcpClient();            this._client.Connect(url, portNo);            data = new byte[this._client.ReceiveBufferSize];            SendMessage(idtext);            this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize),                ReceiveMessage, null);                    }        else        {            Debug.Log("connect failed or connected");        }    }    public void ReceiveMessage(IAsyncResult ar) {        try        {            int bytesRead;            bytesRead = this._client.GetStream().EndRead(ar);            if (bytesRead < 1)            {                return;            }            else            {                Debug.Log(System.Text.Encoding.UTF8.GetString(data, 0, bytesRead));                string message = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);            }        }        catch (Exception ex)        {        }    }    public void SendMessage(string message) {        if (connect)        {            try            {                                NetworkStream ns = this._client.GetStream();                byte[] data = System.Text.Encoding.UTF8.GetBytes(message);                ns.Write(data, 0, data.Length);                ns.Flush();            }            catch (Exception ex)            {            }        }        else        {            Debug.Log("not connect");        }    }    }

然后在主场景中 设置两个输入框 一个输入id 一个输入交互信息   两个按钮 绑定登录还有发送消息方法



主场景代码

public InputField id;    public InputField message;    public void login()    {        Socket.instance.idtext= id.text;        Socket.instance.login();    }    public void sendmessage()    {        Socket.instance.SendMessage("+"+message.text);    }



最后很low的效果

阅读全文
0 0
原创粉丝点击