C#聊天服务器

Program : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

/// <summary>
/// 基于TCP的socket的长连接
/// </summary>
namespace ServerVr40
{
    class Program
    {
        static void Main(string[] args)
        {
            ChatServer chat = new ChatServer();
        }

        
    }

}

ChatServer :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServerVr40
{
    class ChatServer
    {
        static TcpListener listener;
        static object obj = new object();

        //public static List<RemoteClient> clients = new List<RemoteClient>();
        //存取连接服务器的客户端
        public static Dictionary<EndPoint, RemoteClient> clients = new Dictionary<EndPoint, RemoteClient>();
        public ChatServer()
        {
            //开启服务器侦听
            IPAddress ip = IPAddress.Parse("192.168.112.34");
            //端口号
            int port = 8806;
            listener = new TcpListener(ip, port);
            //开始侦听
            listener.Start();
            Console.WriteLine("聊天室开启.正在等待客户端连接...");

            //获取连接客户端
            listener.BeginAcceptTcpClient(OnAsyncTcpClient, null);

            //开启延迟线程
            Thread thread1 = new Thread(Loop);
            thread1.Start();
        }


        private static void Loop()
        {
            while (true)
            {
                Thread.Sleep(100);
            }
        }

        //异步获取客户端
        private static void OnAsyncTcpClient(IAsyncResult ar)
        {
            //获取连接的客户端
            TcpClient client = listener.EndAcceptTcpClient(ar);
            //获取客户端 IP+端口号
            EndPoint endPoint = client.Client.RemoteEndPoint;



            //分配一个客户端消息接收器
            RemoteClient remote = new RemoteClient(client);
            //将客户端存入字典中
            if (!clients.ContainsKey(endPoint))
            {
                clients.Add(endPoint, remote);
                string welcome = "欢迎" + endPoint + "进入直播间,鱼丸五百,火箭一千,炸弹一万,飞船十万,先充先送,没有优惠!";
                OnWrite(null, welcome);
            }

            lock (obj)
            {
                listener.BeginAcceptTcpClient(OnAsyncTcpClient, null);
            }
        }

        //广播消息给客户端
        static Thread thread;
        public static void OnWrite(EndPoint endPoint, string msg)
        {

            thread = new Thread(() =>
            {
                byte[] buffer = Encoding.UTF8.GetBytes(endPoint + ":\n  " + msg);
                //判断需要发送的客户端

                foreach (var item in clients)
                {
                    //判断不是发送消息的客户端           
                    if (item.Key != endPoint)
                    {
                        //广播消息
                        clients[item.Key].client.GetStream().Write(buffer, 0, buffer.Length);
                    }
                }
                thread.Abort();

            });
            thread.Start();
        }

        //离线用户
        public static void OfflinePoint(EndPoint endPoint)
        {
            Console.WriteLine();
            clients.Remove(endPoint);
            string msg = endPoint + "退出了聊天室...";
            OnWrite(null, msg);
        }
    }
}

RemoteClient :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ServerVr40
{
    class RemoteClient
    {
        public TcpClient client;
        public NetworkStream stream;

        static object obj = new object();

        private const int bufferSize = 1024 * 4;
        private byte[] buffer = new byte[bufferSize];

        public RemoteClient(TcpClient client)
        {
            Console.WriteLine("获取连接IP中...");
            this.client = client;

            Console.WriteLine(client.Client.RemoteEndPoint + "进入聊天室");

            stream = client.GetStream();
            //获取聊天消息中
            stream.BeginRead(buffer, 0, bufferSize, OnAsyncRead, null);

        }

        //异步读
        private void OnAsyncRead(IAsyncResult ar)
        {
            try
            {
                //解析消息
                int readCount = stream.EndRead(ar);
                string msg = Encoding.UTF8.GetString(buffer,0,readCount);
                Console.WriteLine(client.Client.RemoteEndPoint + ":\n   " + msg);

                //广播消息
                ChatServer.OnWrite(client.Client.RemoteEndPoint, msg);

                //清空数组
                Array.Clear(buffer,0, bufferSize);
                //回调,等待下一次接收
                lock (stream)
                {
                    stream.BeginRead(buffer, 0, bufferSize, OnAsyncRead, null);
                }

            }
            catch (Exception e)
            {
                ChatServer.OfflinePoint(client.Client.RemoteEndPoint);
                
            }
        }       
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值