Loading

C#Socket通讯(2)

前言
前面已经把游戏的服务端UI搭起来来了,现在需要实现的就是编写服务端控制器与客户端的代码,实现服务端与客户端的数据传输,并将传输情况显示在服务端的UI上

服务端控制器完整代码

private static Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static Thread thread;
        private static Thread r_thred;
        private static int MaxListen = 1;//最大连入客户端,0无限
        private static bool ServerOpen = false;

        public static List<ClientInfo> Clientlist = new List<ClientInfo>();//用户集合

        // GET: WebSocket
        public ActionResult Index()
        {
            if (ServerOpen == false)
            {
                OpenServer("192.168.64.1", 8090);
            }
            return View();
        }

        //得到在线人数
        public ActionResult OnlineNumber()
        {
            return Json(Clientlist.Count, JsonRequestBehavior.AllowGet);
        }

        //得到客户的地址
        public ActionResult ClientInfodata()
        {
            if (Clientlist.Count != 0)
            {
                //var ClientData = new { ClientRemoteEndPoint = Clientlist[0].ClientRemoteEndPoint };
                return Json(Clientlist[0].ClientRemoteEndPoint.ToString(), JsonRequestBehavior.AllowGet);
            }else
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
            
            
        }

        //得到状态以及消息
        public ActionResult getMsg()
        {
            var data = new { DateTimeS = ReturnJson.DateTimeS, StateCodeI = ReturnJson.StateCodeI, StateTextS = ReturnJson.StateTextS, DataO = ReturnJson.DataO };
            return Json(data, JsonRequestBehavior.AllowGet);
        }



        //关闭服务方法
        public void CloseServer()
        {
            try
            {
                //socketWatch.Close();
                //ServerOpen = false;

                ReturnJson.DateTimeS = DateTime.Now.ToString();
                ReturnJson.StateCodeI = 10;
                ReturnJson.StateTextS = "服务端已关闭!";
                ReturnJson.DataO = null;
            }
            catch (SocketException e)
            {
                ReturnJson.DateTimeS = DateTime.Now.ToString();
                ReturnJson.StateCodeI = 20;
                ReturnJson.StateTextS = "服务端出现异常!Error:" + e.ToString();
                ReturnJson.DataO = null;
            }

        }

        //开启服务方法
        public void OpenServer(string IP, int Port)
        {
                try
                {
                    IPAddress iPAddress = IPAddress.Parse(IP);
                    IPEndPoint iPEnd = new IPEndPoint(iPAddress, Port);
                    socketWatch.Bind(iPEnd);
                    socketWatch.Listen(MaxListen);
                    thread = new Thread(Listen);
                    thread.IsBackground = true;
                    thread.Start(socketWatch);
                    ServerOpen = true;
                    ReturnJson.DateTimeS = DateTime.Now.ToString();
                    ReturnJson.StateCodeI = 100;
                    ReturnJson.StateTextS = "服务端准备就绪,等待连接!";
                    ReturnJson.DataO = IP + ":" + Port;

                }
                catch (SocketException e)
                {
                    ReturnJson.DateTimeS = DateTime.Now.ToString();
                    ReturnJson.StateCodeI = 20;
                    ReturnJson.StateTextS = "服务端出现异常!Error:" + e.ToString();
                    ReturnJson.DataO = null;
                }
        }

        //服务端等待客户端的连接
        private static Socket socketSend;
        public void Listen(object o)
        {
            try
            {
                Socket socketWatch = o as Socket;
                while (true)
                {
                    socketSend = socketWatch.Accept();
                    r_thred = new Thread(Received);
                    r_thred.IsBackground = true;
                    r_thred.Start(socketSend);
                    ClientInfo clientInfo = new ClientInfo() { ClientRemoteEndPoint = socketSend.RemoteEndPoint.ToString()};

                    Clientlist.Add(clientInfo);

                    ReturnJson.DateTimeS = DateTime.Now.ToString();
                    ReturnJson.StateCodeI = 120;
                    ReturnJson.StateTextS = "服务端已和客户端连接!";
                    ReturnJson.DataO = null;

                }

            }
            catch (SocketException e)
            {
                ReturnJson.DateTimeS = DateTime.Now.ToString();
                ReturnJson.StateCodeI = 20;
                ReturnJson.StateTextS = "服务端出现异常!Error:" + e.ToString();
                ReturnJson.DataO = null;
            }
        }

        //服务端等待客户端的消息
        public void Received(object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        ReturnJson.DateTimeS = DateTime.Now.ToString();
                        ReturnJson.StateCodeI = 20;
                        ReturnJson.StateTextS = "客户端已断开连接!";
                        ReturnJson.DataO = null;
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    ReturnJson.DateTimeS = DateTime.Now.ToString();
                    ReturnJson.StateCodeI = 140;
                    ReturnJson.StateTextS = "接收到客户端请求";
                    ReturnJson.DataO = str;
                }
            }
            catch (SocketException e)
            {
                ReturnJson.DateTimeS = DateTime.Now.ToString();
                ReturnJson.StateCodeI = 20;
                ReturnJson.StateTextS = "服务端出现异常!Error:" + e.ToString();
                ReturnJson.DataO = null;
            }
        }

        //服务端发送消息给所有客户端
        public void Send(string str)
        {
            if(Clientlist.Count != 0)
            {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
            ReturnJson.DateTimeS = DateTime.Now.ToString();
            ReturnJson.StateCodeI = 200;
            ReturnJson.StateTextS = "服务端已发送数据!";
            ReturnJson.DataO = str;
            }else
            {
                ReturnJson.DateTimeS = DateTime.Now.ToString();
                ReturnJson.StateCodeI = 20;
                ReturnJson.StateTextS = "当前没有客户端在线,消息没发送出去!";
                ReturnJson.DataO = null;
            }
        }

客户端完整代码
public string IP = "";
    public int Port = 0;
    private static Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    private static Thread thread;
    private static Thread r_thread;

    private void Start()
    {
        ConnectionServer();
    }
    public void ConnectionServer()
    {
        try
        {
            IPAddress iPAddress = IPAddress.Parse(IP);
            IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, Port);
            socketWatch.Connect(iPEndPoint);
        }
        catch (SocketException)
        {

        }
    }
    private static Socket socketSend;
    public void SendData()
    {
        //ConnectionServer();
        string Str = GameObject.Find("Canvas/InputField").GetComponent<InputField>().text;
        byte[] bytestr = Encoding.UTF8.GetBytes(Str);
        socketWatch.Send(bytestr, bytestr.Length, 0);
        thread = new Thread(ReceiveData);
        thread.IsBackground = true;
        thread.Start();
    }

    public void ReceiveData()
    {
        string recvStr = "";
        int bytes;
        byte[] bytestr = new byte[1024];
        bytes = socketWatch.Receive(bytestr, bytestr.Length, 0);
        recvStr += Encoding.UTF8.GetString(bytestr, 0, bytes);
        Debug.Log(recvStr);
        
}

我们先启动服务端进行监听
在这里插入图片描述
打开客户端
在这里插入图片描述
服务端检测到客户端上线
在这里插入图片描述
客户端发送消息给服务端
在这里插入图片描述
服务端发送消息给客户端
在这里插入图片描述
服务端检测到客户端下线
在这里插入图片描述
后言
我们现在已经完成服务端与客户端的通讯了,如果觉得本技术文章对你有帮助请给我点个赞,如果有什么不足的地方,给我提意见,让我加以改进

posted @ 2019-05-08 15:51  LRolinx  阅读(136)  评论(0编辑  收藏  举报