Socket强联网聊天

服务器

using System;
using System.Collections.Generic;
using System.Linq;
usingSystem.Net;
using System.Text;
using System.Threading.Tasks;
namespace qunChatServer
{
    class NetMgr : Singleton<NetMgr>
    {
        public Socket lister;
        public byte[] buffer = new byte[2048];
        public List<Socket> list = new List<Socket>();
                                                              
        /// <summary>
        ///开启服务器的方法
        /// </summary>
        public void StartServer()
        {
        lister = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            lister.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777));
            lister.Listen(0);
            Console.WriteLine("服务器已经开启侦听>>>>>>>");
            lister.BeginAccept(Acceptcallback, null);
        }
        private void Acceptcallback(IAsyncResult ar)
        {
            Socket client = lister.EndAccept(ar);
            IPEndPoint iep = (IPEndPoint)client.RemoteEndPoint;
     Console.WriteLine("有客户端连入了,其ip为:{0},端口号为:{1}", iep.Address.ToString(), iep.Port);
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
        }
        /// <summary>
        /// 接收
        /// </summary>
        /// <param name="ar"></param>
        private void Receivecallback(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState;
            list.Add(client);
            int len = client.EndReceive(ar);
            try
            {
                if (len > 0)
                {
                    byte[] newbuffer = new byte[len];
                    Buffer.BlockCopy(buffer, 0, newbuffer, 0, newbuffer.Length);
                    string str = Encoding.UTF8.GetString(newbuffer);
                    Console.WriteLine("收到数据了,其内容为 :{0},长度为:{1}", str, newbuffer.Length);
                    foreach (Socket item in list)
                    {
                        SendMsg(item, str);
                    }
                    lister.BeginAccept(Acceptcallback, null);
                    client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
                   
                }
                else
                {
                    CloseClient(client);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(client.LocalEndPoint + "连接失败!" + ex.Message);
            }
        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="item"></param>
        /// <param name="str"></param>
        private void SendMsg(Socket item, string str)
        {
            byte[] b = Encoding.UTF8.GetBytes(str);
            item.Send(b);
        }
        private void CloseClient(Socket client)
        {
            Console.WriteLine(client.LocalEndPoint + "断开连接了");
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
    }
}




客户端

using System;
using System.Collections;
using System.Collections.Generic;
usingSystem.Net;
using System.Text;
using UnityEngine;
public class NetMgr : singleton<NetMgr>
{
    public Socket client;
    public byte [] buffer = new byte [2048];
    public Queue< string > queue = new Queue< string >();
    /// <summary>
    /// 开启客户端的方法
    /// </summary>
    public void StartClient()
    {
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect( new IPEndPoint(IPAddress.Parse( "127.0.0.1" ), 7777));
        if (client.Connected)
        {
            Debug.Log(client.LocalEndPoint + "连接成功" );
        }
    }
    public void ReceiveMsg()
    {
        client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
    }
    /// <summary>
    /// 接收
    /// </summary>
    /// <param name=" ar "></param>
    private void Receivecallback(IAsyncResult ar)
    {
        Socket client = (Socket)ar.AsyncState;
        int len = this .client.EndReceive(ar);
        try
        {
            if (len > 0)
            {
                byte [] newbuffer = new byte [len];
                Buffer.BlockCopy(buffer, 0, newbuffer, 0, newbuffer.Length);
                string str = Encoding.UTF8.GetString(newbuffer);
                Debug.Log( "收到数据了,其内容为:" + str);
                queue.Enqueue(str);//入队
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
            }
            else
            {
                CloseClient(client);
            }
        }
        catch (Exception ex)
        {
            Debug.Log(client.LocalEndPoint + "连接失败!" + ex.Message);
        }
    }
    /// <summary>
    /// 发送信息
    /// </summary>
    /// <param name=" item "></param>
    /// <param name=" str "></param>
    public void SendMsg( string str)
    {
        byte [] b = Encoding.UTF8.GetBytes(str);
        client.Send(b);
    }
    private void CloseClient(Socket client)
    {
        Debug.Log(client.LocalEndPoint + "断开连接了" );
        client.Shutdown(SocketShutdown.Both);
        client.Close();
    }

}

挂载在UI上
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChatUI : MonoBehaviour
{
    public UITextList list;
    public UIInput input;
    public UIButton btn;
    void Start ()
    {
        UIEventListener.Get(btn.gameObject).onClick+=OnbtnClick;
        NetMgr.instance.StartClient();
        NetMgr.instance.ReceiveMsg();
    }
    private void OnbtnClick(GameObject go)
    {
        string msg = input.value;
        if (! string .IsNullOrEmpty(msg))
        {
            NetMgr.instance.SendMsg(NetMgr.instance.client+"说:"+msg);
        }
    }
    void Update ()
    {
        if (NetMgr.instance.queue.Count>0) //队列大于0
        {
            list.Add(NetMgr.instance.queue.Dequeue());//出队
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值