Socket通信 群聊


用json解析 所以得加载个ListJson
服务器
//主类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        NetMannger.Instance.Init();
        NetMannger.Instance.StartNet();
        Console.ReadKey();
    }
}
//委托
using LitJson;
public delegate void MsgHand(JsonData data);
//网络管理器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using LitJson;
public class NetMannger
{
    private static NetMannger instance;
    public static NetMannger Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new NetMannger();
            }
            return instance;
        }
    }
    List<Socket> sockets = new List<Socket>();
    byte[] b = new byte[1024];
    Socket server;
    Dictionary<string, MsgHand> hands = new Dictionary<string, MsgHand>();
    public void StartNet()
    {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1112);
        server.Bind(ipEP);
        server.Listen(10);
        Console.WriteLine("服务器开始监听");
        server.BeginAccept(AcceptHand, null);
    }
    private void AcceptHand(IAsyncResult ar)
    {
        Socket client = server.EndAccept(ar);
        sockets.Add(client);
        Console.WriteLine("有客户端连入ip为" + ((IPEndPoint)client.RemoteEndPoint).Address.ToString() + "port为" + ((IPEndPoint)client.RemoteEndPoint).Port.ToString());
        client.BeginReceive(b, 0, b.Length, SocketFlags.None, ReceiveHand, client);
        server.BeginAccept(AcceptHand, null);
    }
    private void ReceiveHand(IAsyncResult ar)
    {
        Socket client = ar.AsyncState as Socket;
        int len = client.EndReceive(ar);
        byte[] data = new byte[len];
        Array.Copy(b, 0, data, 0, len);
        JsonData msgs = JsonMapper.ToObject(Encoding.UTF8.GetString(data));
        string pro = msgs["pro"].ToString();
        MsgHand hand;
        hands.TryGetValue(pro,out hand);
        if (hand != null)
            hand(msgs);
        client.BeginReceive(b, 0, b.Length, SocketFlags.None, ReceiveHand, client);
    }
    public void SendMsg(byte[] b)
    {
        foreach (var item in sockets)
        {
            item.Send(b);
        }
    }
    public void Init() {
        ChatMoudle chat = new ChatMoudle();
        hands.Add("10001",chat.PublicChat);
    }
}
//聊天模块
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
public class ChatMoudle
{
    public void PublicChat(JsonData data) {
        JsonData newdata = new JsonData();
        newdata["pro"] = "10001";
        newdata["msg"] = data["msg"].ToString();
        NetMannger.Instance.SendMsg(Encoding.UTF8.GetBytes(newdata.ToJson()));
    }
}


客户端



//委托
using LitJson;
public delegate void _430MsgHand(JsonData data);

//网络管理器
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
public class _430NetMannger {
    private static _430NetMannger instance;
    public static _430NetMannger Instance
    {
        get
        {
            if (instance == null) {
                instance = new _430NetMannger();
            }
            return instance;
        }
    }
    Socket client;
    byte[] b = new byte[1024];
    public Queue<byte[]> msgs = new Queue<byte[]>();
    public void StartNet() {
        client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        IPEndPoint ipEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1112);
        client.Connect(ipEP);
        if (client.Connected) {
            Debug.Log("连接服务器成功");
        }
        client.BeginReceive(b,0,b.Length,SocketFlags.None,ReceiveHand, null);
    }
  
    private void ReceiveHand(IAsyncResult ar)
    {
        int len = client.EndReceive(ar);
        byte[] data = new byte[len];
        Array.Copy(b,0,data,0,len);
        msgs.Enqueue(data);
        client.BeginReceive(b, 0, b.Length, SocketFlags.None, ReceiveHand, null);
    }
    public void SendMsg(byte[] data) {
        client.Send(data);
    }
}

//聊天界面
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.Text;
public class _430ChanePlane : MonoBehaviour {
    public UITextList tl;
    public UILabel l;
 void Start () {
        _430NetMannger.Instance.StartNet();
 }
 
 // Update is called once per frame
 void Update () {
        if (_430NetMannger.Instance.msgs.Count > 0) {
            byte[] b = _430NetMannger.Instance.msgs.Dequeue();
            string temp = Encoding.UTF8.GetString(b);
            JsonData data = JsonMapper.ToObject(temp);
            if (data["pro"].ToString() == "10001") {
                tl.Add(data["msg"].ToString());
            }
        }
 }
    public void Send() {
        JsonData data = new JsonData();
        data["pro"] = "10001";
        data["msg"] = l.text;
        _430NetMannger.Instance.SendMsg(Encoding.UTF8.GetBytes(data.ToJson()));
        l.text = "";
    }
}

猜你喜欢

转载自blog.csdn.net/itliruochong/article/details/80148435