C# Tcpclient Tcplistener 服务器接收多个客户端消息通讯

一、服务器端

        为了接受多个客户端的连接请求,我们使用BeginAcceptTcpClient方法来异步接收,然后在异步回调中再次启用接收,以递归的方法实现接收多个客户端的接入请求。以命令窗作为服务器,具体代码如下:

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

namespace SocketTest
{
    class Program
    {

        private static byte[] result = new byte[1024];
        private const int port = 8088;
        private static string IpStr = "127.0.0.1";
        private static TcpListener server;

        public static List<TcpClient> clients=new List<TcpClient>();

        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse(IpStr);
            IPEndPoint ip_end_point = new IPEndPoint(ip, port);
            //=============================================================
            server = new TcpListener(ip_end_point);
            server.Start();
            Console.WriteLine("启动监听成功");

            server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);//异步接收 递归循环接收多个客户端
            Console.ReadKey();
        }
        //异步回调方法
        private static void DoAcceptTcpclient(IAsyncResult ar)
        {
            // Get the listener that handles the client request.
            TcpListener listener = (TcpListener)ar.AsyncState;

            // End the operation and display the received data on 
            // the console.
            TcpClient client = listener.EndAcceptTcpClient(ar);

            clients.Add(client);

            // Process the connection here. (Add the client to a
            // server table, read data, etc.)
            Console.WriteLine("Client connected completed,id:{0}",client.Client.RemoteEndPoint.ToString());
            //开启线程用来不断接收来自客户端的数据
            Thread t=new Thread(new ParameterizedThreadStart(ReceiveMessageFromClient));
            t.Start(client);

            server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);
        }

        private static void ReceiveMessageFromClient(object reciveClient)
        {
            TcpClient client = reciveClient as TcpClient;
            if (client == null)
            {
                Console.WriteLine("client error");
                return;
            }
            while (true)
            {
                try
                {
                    NetworkStream stream = client.GetStream();
                    Console.WriteLine("waiting for data...");
                    int num = stream.Read(result, 0, result.Length); //将数据读到result中                  
                    if (num != 0)
                    {
                        string str = Encoding.UTF8.GetString(result,0,num);//只将流中读到的数据长度转换为字符串
                        Console.WriteLine("数据长度:{0},数据内容:{1}", num, str);
                    }
                    else
                    {   //这里需要注意 当num=0时表明客户端已经断开连接,需要结束循环,不然会死循环一直卡住 
                        Console.WriteLine("客户端关闭");
                        break;
                    }
                }
                catch (Exception e)
                {
                    clients.Remove(client);
                    Console.WriteLine("error:" + e.ToString());
                    break;
                }

            }

        }
        //================================================================================

    }
}

二、客户端

        以unity作为客户端,具体代码如下:

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using SocketTest;

public class SocketTestUnity : MonoBehaviour
{
    private TcpClient client;
    public const int port = 8800;
    public string ip = "127.0.0.1";
    private NetworkStream stream;

	// Use this for initialization
	void Start () {
        IPEndPoint i = new IPEndPoint(IPAddress.Parse(ip), port);
        client = new TcpClient(i);
        client.Connect(ip, 8088);
        stream = client.GetStream();
        string msg = "hahaha";
        byte[] bytes = Encoding.UTF8.GetBytes(msg);
        stream.Write(bytes, 0, bytes.Length);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            print("aaa");
            string msg = "aaaaaa";
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            stream.Write(bytes, 0, bytes.Length);
        }
    }

}

以上只是简单实现通讯。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值