Crystal‘s Unity Notes:服务器与客户端

服务器

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;  //网络通讯的代码需要加这两个命名空间
using System.Net.Sockets;
using System.Threading;

namespace soket服务器
{
    class Program
    {
        static byte[] messageArr = new byte[1024];
        static List<Socket> clientList = new List<Socket>();
        static void Main(string[] args)
        {
            //Socket;一个类,封装了网络通讯需要的数据的一个集合
            //地址族                   Socket类型 Stream是给TCP用的,Dgram是给UDP协议用的,Protocol协议
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //IP地址 和 端口号
            //127.0.0.1
            string ip = "127.0.0.1";
            int port = 8888;
            //绑定接收的地址
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            serverSocket.Listen(0);//服务器开始运行了
            Console.WriteLine("服务器启动了");

            while (true)
            {
                //服务器连接上一个客户端
                Socket clientSocket = serverSocket.Accept();//阻塞式函数
                clientList.Add(clientSocket);
                Console.WriteLine("连接到的客户端的信息为" + clientSocket.RemoteEndPoint.ToString());
                //服务器向客户端发送已经连接好的消息
                string message = "同志你好,已经连接上了";
                byte[] msgArr = Encoding.UTF8.GetBytes(message); //将字符串类型转换为UTF8编码下的二进制数据
                clientSocket.Send(msgArr);
                //服务器接受客户端发过来的信息
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        while (true)
                        {
                            int length = clientSocket.Receive(messageArr);
                            if(length == 0)
                            {
                                clientList.Remove(clientSocket);
                                clientSocket.Close();
                                return;
                            }
                            string msg = Encoding.UTF8.GetString(messageArr, 0, length);
                            Console.WriteLine(msg);
                            for (int i = 0; i < clientList.Count; i++)
                            {
                                //判断是否为自身(发送给除了自身以外的其他客户端)
                                if (clientList[i] != clientSocket)
                                {
                                    clientList[i].Send(Encoding.UTF8.GetBytes(msg));
                                }
                            }
                        }
                    }

                    catch (Exception)
                    {
                        clientList.Remove(clientSocket);
                        clientSocket.Close();                    
                    }
                });
                thread.Start();
            }
        }
    }
}

服务器异步连接

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

namespace 服务器异步链接
{
    class Program
    {
        static List<Socket> clientList = new List<Socket>();
        static byte[] msgArr = new byte[1024];
        static void Main(string[] args)
        {
            //异步连接:本质上就是多线程。
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
            serverSocket.Listen(0);
            Console.WriteLine("服务器启动了");

            //用异步连接来接受客户端
            serverSocket.BeginAccept(AsyncAccept, serverSocket);
            while (Console.ReadLine()== "c")
            {
                break;
            }
            Console.WriteLine("服务器终止了");
        }

        private static void AsyncAccept(IAsyncResult ar)
        {
            Socket serverSocket = ar.AsyncState as Socket;
            Socket clientSocket = serverSocket.EndAccept(ar);
            clientList.Add(clientSocket);
            //不停的接受客户端发来的消息
            clientSocket.BeginReceive(msgArr, 0, msgArr.Length, SocketFlags.None, AsyncReceive, clientSocket);
            serverSocket.BeginAccept(AsyncAccept, serverSocket); //尾递归
        }

        private static void AsyncReceive(IAsyncResult ar)
        {
            Socket clientSocket = ar.AsyncState as Socket;
            try
            {
                int length = clientSocket.EndReceive(ar);
                if (length == 0)
                {
                    clientList.Remove(clientSocket);
                    clientSocket.Close();
                    return;
                }
                string msg = Encoding.UTF8.GetString(msgArr, 0, length);
                Console.WriteLine(msg);
                for (int i = 0; i < clientList.Count; i++)
                {
                    if (clientList[i] != clientSocket)
                    {
                        clientList[i].Send(Encoding.UTF8.GetBytes(msg));
                    }
                }
                clientSocket.BeginReceive(msgArr, 0, msgArr.Length, SocketFlags.None, AsyncReceive, clientSocket);
            }
            catch (Exception)
            {
                clientList.Remove(clientSocket);
                clientSocket.Close();
            }
        }
    }
}

 客户端 

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


namespace Socket客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.2.69"), 8888));

            Console.WriteLine("请输入你的名字");
            string name = Console.ReadLine();
            byte[] msgArr = new byte[1024];

            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    int length = clientSocket.Receive(msgArr); //阻塞式函数
                    string msg = Encoding.UTF8.GetString(msgArr, 0, length);
                    Console.WriteLine(msg);
                }
            });
            thread.Start();

            while (true)
            {
                string message = Console.ReadLine();
                message = name + ":" + message;
                byte[] array = Encoding.UTF8.GetBytes(message);
                clientSocket.Send(array);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值