Socket学习下

版权声明:转载 请说明 出处 https://blog.csdn.net/qq2512667/article/details/86512725
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
namespace Socket_聊天室_socketTcp服务端
{
    public class Client
    {
        private Socket m_client;
        byte[] data = new byte[1024];
        string mes = "";
        Thread t;
        public Client(Socket client)
        {
            m_client = client;
            t = new Thread(SendMess);
            t.Start();
        }

        void SendMess()
        {
            while (true)
            {
                if (m_client.Poll(10, SelectMode.SelectRead))
                {
                    m_client.Close();
                    break;
                }
                int count = m_client.Receive(data);
                mes = Encoding.UTF8.GetString(data, 0, count);
                Console.WriteLine("服务器收到客服端的消息:" + mes);
                //广播消息
                Program.BoradCastMessage(mes);
            }

         
        }
        public void SendMsg(string msg)
        {
            m_client.Send(Encoding.UTF8.GetBytes(mes));
        }
        public bool isConnect { get { return m_client.Connected; } }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace Socket_聊天室_socketTcp服务端
{
    class Program
    {
        public static List<Client> clients = new List<Client>(); 
        static void Main(string[] args)
        {
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            EndPoint endPoint = new IPEndPoint(IPAddress.Parse("172.17.144.3"), 7788);
            tcpServer.Bind(endPoint);

            tcpServer.Listen(100);
            Console.WriteLine("开始监听");
            while (true)
            {
                
                Socket socket= tcpServer.Accept();
                Client client = new Client(socket);
                Console.WriteLine("a client");
                Console.WriteLine("一个新的客户端连接进来了"); 
                clients.Add(client);
                //....
            }
        }
        //广播消息
        public static void BoradCastMessage(string mes)
        {
            List<Client> notConnect = new List<Client>();
            foreach (var  item in clients)
            {
                if (item.isConnect)
                {
                    item.SendMsg(mes);
                }
                else
                {
                    notConnect.Add(item);
                }
            }
            foreach (var item in notConnect )
            {
                clients.Remove(item);
            }
        }
    }
}

没链接进来一个客服端   服务器就会 进行 存储,在广播的时候,如果失去链接了,就会从列表中移除;

下面是Unity中的设置

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

public class MyChat : MonoBehaviour {

	// Use this for initialization
	public string ipAddress;
	public int port;

    byte[] data = new byte[1024];

	Socket client;
	public UIInput input;
	public UILabel label;
    Thread t;
    string mes = "";
	void Start () {
        ConnectToServer();
  
	}

    void ConnectToServer()
    {
        ipAddress = "172.17.144.3";
        port = 7788;
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(IPAddress.Parse(ipAddress), port);
        
        //接受消息
        t = new Thread(ReceiveMes);
        t.Start();
    }
    public void OnSendButtonClick()
	{
        string val = input.value;
        client.Send(Encoding.UTF8.GetBytes(val));
        input.value = "";
	}

    public void ReceiveMes()
    {
        while (true)
        {
            if (client.Connected==false)
            {
                client.Close();
                break;
            }
            int length = client.Receive(data);
            mes = Encoding.UTF8.GetString(data, 0, length);
        }        
    }
    
    private void OnDestroy()
    {
        client.Shutdown(SocketShutdown.Both);
        client.Close();  
    }

    // Update is called once per frame
    void Update ()
    {
        if (mes!=""&&mes!=null)
        {
            label.text += "\n" + mes;
            mes = "";
        }
	}
}

猜你喜欢

转载自blog.csdn.net/qq2512667/article/details/86512725