C# 服务器,客户端 1:N模式

服务器RemoteClient

using System;
using System.Net.Sockets;
using System.Text;
using System.Linq;

namespace Server
{
    class RemoteClient
    {
        private TcpClient client;
        private NetworkStream streamToClient;
        private const int BufferSize = 8192;
        private byte[] buffer;
        private int currentId;

        public RemoteClient(TcpClient client)
        {
            this.client = client;
            currentId = Program.dictInfo.Where(q => q.Value == client.Client.RemoteEndPoint.ToString()).Select(q => q.Key).ElementAt(0);

            Console.WriteLine("\n客户端已连接!{0} <-- {1}",
     client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

            streamToClient = client.GetStream();
            buffer = new byte[BufferSize];

            AsyncCallback callBack = new AsyncCallback(ReadComplete);
            streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
        }

        private void ReadComplete(IAsyncResult ar)
        {
            int bytesRead = 0;
            try
            {
                lock (streamToClient)
                {
                    bytesRead = streamToClient.EndRead(ar);
                }
                if (bytesRead == 0) throw new Exception("读取到0字节");

                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Array.Clear(buffer, 0, buffer.Length);

                string[] arrayMsg = msg.Split(new string[] { "$" }, StringSplitOptions.None);
                int clientId = int.Parse(arrayMsg[0]);

                if (clientId >= 100)
                {
                    try
                    {
                        NetworkStream destStream = Program.dict[clientId].GetStream();
                        byte[] destMsg = Encoding.Unicode.GetBytes("来自" + currentId + "的信息:" + arrayMsg[1]);
                        destStream.Write(destMsg, 0, destMsg.Length);
                        destStream.Flush();
                        Console.WriteLine("收到<{0}>信息转发到<{1}>: {2}", currentId, clientId, arrayMsg[1]);
                    }
                    catch (Exception)
                    {
                        byte[] destMsg = Encoding.Unicode.GetBytes("<" + clientId + ">下线了,发送失败");
                        streamToClient.Write(destMsg, 0, destMsg.Length);
                        streamToClient.Flush();
                    }
                }
                else
                {
                    byte[] destMsg = Encoding.Unicode.GetBytes("<" + currentId + ">" + arrayMsg[1]);
                    streamToClient.Write(destMsg, 0, destMsg.Length);
                    streamToClient.Flush();
                    Console.WriteLine("收到<{0}>信息: {1}", currentId, arrayMsg[1]);
                }

                lock (streamToClient)
                {
                    AsyncCallback callBack = new AsyncCallback(ReadComplete);
                    streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
                }
            }
            catch (Exception ex)
            {
                if (streamToClient != null)
                    streamToClient.Dispose();
                client.Close();
                Console.WriteLine(ex.Message);
            }
        }
    }
}

服务器main

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    class Program
    {
        public static Dictionary<int, TcpClient> dict = new Dictionary<int, TcpClient>();
        public static Dictionary<int, string> dictInfo = new Dictionary<int, string>();
        static void Main(string[] args)
        {
            Console.WriteLine("服务器开始运行 ... ");
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener listener = new TcpListener(ip, 8500);

            listener.Start();
            Console.WriteLine("开始侦听 ...");

            int clientId = 100;
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                dict.Add(clientId, client);
                dictInfo.Add(clientId, client.Client.RemoteEndPoint.ToString());
                clientId++;
                RemoteClient wapper = new RemoteClient(client);
            }
        }
    }
}

客户端ServerClient

using System;
using System.Net.Sockets;
using System.Text;

namespace Client
{
    class ServerClient
    {
        private const int BufferSize = 8192;
        private byte[] buffer;
        private TcpClient client;
        private NetworkStream streamToServer;
        private string msg = "";

        public ServerClient()
        {
            try
            {
                client = new TcpClient();
                client.Connect("localhost", 8500);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            buffer = new byte[BufferSize];

            Console.WriteLine("已连接到服务器!{0} --> {1}",
     client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

            streamToServer = client.GetStream();
        }

        public void SendMessage(string msg)
        {
            byte[] temp = Encoding.Unicode.GetBytes(msg);
            try
            {
                streamToServer.Write(temp, 0, temp.Length);
                Console.WriteLine("发送信息: {0}", msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            lock (streamToServer)
            {
                AsyncCallback callBack = new AsyncCallback(ReadComplete);
                streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
            }
        }

        public void SendMessage()
        {
            SendMessage(this.msg);
        }

        private void ReadComplete(IAsyncResult ar)
        {
            int bytesRead;

            try
            {
                lock (streamToServer)
                {
                    bytesRead = streamToServer.EndRead(ar);
                }
                if (bytesRead == 0) throw new Exception("读取到0字节");

                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Console.WriteLine("收到信息: {0}", msg);
                Array.Clear(buffer, 0, buffer.Length);

                lock (streamToServer)
                {
                    AsyncCallback callBack = new AsyncCallback(ReadComplete);
                    streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
                }
            }
            catch (Exception ex)
            {
                if (streamToServer != null)
                    streamToServer.Dispose();
                client.Close();

                Console.WriteLine(ex.Message);
            }
        }
    }
}

客户端main

using System;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerClient client = new ServerClient();
            client.SendMessage("0$初始化连接请求");
            while (true)
            {
                client.SendMessage(Console.ReadLine());
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值