C#Socket通讯聊天完整代码

C#Socket通讯聊天完整代码

话不多说,直接上代码,可以用来做聊天通讯
打开Visual Studio,新建.NetFramework控制台应用程序,复制以下代码新建客户端服务端项目即可食用.

TCP通讯

TCP客户端

 class Program
    {
        static Socket client;

        static void Main(string[] args)
        {
            CreateClient();

            new Thread(() =>
            {
                Thread.Sleep(500);
                SendMessage();
            }).Start();

            new Thread(() =>
            {
                Thread.Sleep(500);
                ReceiveMessage();
            }).Start();

        }

        static void CreateClient()
        {
            try
            {

                IPAddress iPAdress = new IPAddress(new byte[] { 192, 168,6, 41 });
                int port = 8000;
                IPEndPoint iPEndPoint = new IPEndPoint(iPAdress, port);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(iPEndPoint);
                Console.WriteLine("已经连接上服务器");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
                Process.GetCurrentProcess().Close();
            }
        }
		///发送消息
        static void SendMessage()
        {
            try
            {
                while (true)
                {
                    Console.WriteLine("等待发送信息,回车->发送,close->断开连接");
                    string s = Console.ReadLine();
                    client.Send(Encoding.Default.GetBytes(s));
                    Console.WriteLine("发送成功!\n");

                    if (s == "close")
                    {
                        client.Close();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
		///接收消息
        static void ReceiveMessage()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 8];
                    int length = client.Receive(buffer);
                    string msg = Encoding.Default.GetString(buffer, 0, length);
                    if (buffer.Length > 0)
                    {
                        Console.WriteLine("服务器:" + msg);
                    }
                    else
                    {
                        Console.WriteLine("断开连接");
                        break;
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

TCP服务端

class Program
    {
        static Socket server;
       static Socket client;

        static readonly Dictionary<string, Socket> clients = new Dictionary<string, Socket>();

        static void Main()
        {

            CreateServer();

            new Thread(() =>
            {
                try
                {
                    Accept(server);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }).Start();
            new Thread(() =>
            {
                Thread.Sleep(500);
                SendMessage();
            }).Start();
        }
        static void SendMessage()
        {
            try
            {

                while (true)
                {
                    Console.WriteLine("等待发送信息,回车->发送,close->断开连接");
                    string s = Console.ReadLine();
                    foreach (Socket client in clients.Values)
                    {
                        client.Send(Encoding.Default.GetBytes(s));
                    }
                    Console.WriteLine("发送成功!\n");

                    if (s == "close")
                    {
                        client.Close();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        static void CreateServer()
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 6, 41 });
            int port = 8000;
            EndPoint endPoint = new IPEndPoint(iPAddress, port);
            server.Bind(endPoint);
            server.Listen(8);

            Console.WriteLine("tcp端口已经打开,192.168.6.41:8000");
            DisplayAllClients();

        }
		
        static void Accept(Object obj)
        {
            Socket socket = (Socket)obj;
            while (true)
            {
                 client = socket.Accept();
                string ip = client.RemoteEndPoint.ToString();
                if (!clients.ContainsKey(ip))
                {
                    clients.Add(ip, client);
                    Console.WriteLine(ip + "已连接");
                    DisplayAllClients();
                }

                new Thread(() =>
                {
                    try
                    {
                        Recieve(client);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        clients.Remove(ip);
                    }
                })
                { IsBackground = true }.Start();
            }
        }

        static void Recieve(Object obj)
        {
            Socket client = (Socket)obj;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 8];
                    int length = client.Receive(buffer);

                    string message = Encoding.Default.GetString(buffer, 0, length);
                    Console.WriteLine(client.RemoteEndPoint.ToString() + ":" + message);
                    if (message == null || message.Length == 0 || message == "close")
                    {
                        string ip = client.RemoteEndPoint.ToString();
                        Console.WriteLine(ip + "连接断开!");
                        clients.Remove(ip);
                        DisplayAllClients();
                        break;
                    }
                    else
                    {
                       
                       
                    }

                    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    clients.Remove(client.RemoteEndPoint.ToString());
                    DisplayAllClients();
                    break;
                }
            }
        }
		///显示所有连接客户端
        static void DisplayAllClients()
        {
            if (clients.Values.Count == 0)
            {
                Console.WriteLine("目前无连接");
                Console.WriteLine("等待新的连接");
            }
            else
            {
                Console.WriteLine("目前所有连接");
                Console.WriteLine("+==========+");
                foreach (Socket client in clients.Values)
                {
                    Console.WriteLine(client.RemoteEndPoint.ToString());
                }
                Console.WriteLine("+==========+");
                Console.WriteLine();
            }
        }
    }

注意测试IP地址端口号改成自己的IP,对应监听连接的端口号.

UDP通讯

	1. UDP不属于面向连接的通信,在选择协议时,选择UDP必须要谨慎。在网络质量较差情况下,UDP协议数据包丢失会比较严重。但是由于UDP的特性:它不属于连接型协议,具有资源消耗小,处理速度快等优点,所以通常音视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。

    2.通过UDP进行信息收发,并没有严格的客户端和服务端之分,它不同于   TCP,TCP必须建立可靠连接之后才可以通信,而UDP随时都可以给指定的ip和端口所对应进程发送消息。

    3.UDP发送消息时需要绑定自己IP 和 端口号,接收消息的时候没有特殊限制,只要有人给自己发送,自己在线,就可以接收。

    4.总之,使用UDP协议进行信息的传输之前不需要建立连接。换句话说就是客户端向服务器发送信息,客户端只需要给出服务器的ip地址和端口号,然后将信息封装到一个待发送的报文中并且发送出去。至于服务器端是否存在,或者能否收到该报文,客户端根本不用管。 

UDP客户端

internal class Program
    {
        static Socket client;
        static void Main(string[] args)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(new IPEndPoint(IPAddress.Parse("192.168.6.41"), 8000));//绑定端口号和IP
            Thread threadReceiveMsg = new Thread(ReceiveMsg); //开启接收消息线程
            threadReceiveMsg.Start();
            Thread threadSendMsg = new Thread(sendMsg);//开启发送消息线程
            threadSendMsg.Start();
            Console.WriteLine("客户端已开启");
        }
        /// <summary>
        /// 向指定IP的主机端口发送数据报
        /// </summary>
        static void sendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.6.41"), 8001);
            while (true)
            {
                string msg = Console.ReadLine();
                client.SendTo(Encoding.UTF8.GetBytes(msg), point);
            }
        }
        /// <summary>
        /// 接收发送给本机IP对应端口号的数据报
        /// </summary>
        static void ReceiveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的IP和端口号
                byte[] buffer = new byte[1024];
                int length = client.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);
                Console.WriteLine(DateTime.Now.ToString() + "Msg From:" + point.ToString() + ":" + message);
            }
        }
    }

UDP服务端

 internal class Program
    {
        static Socket server;
        static void Main(string[] args)
        {
            server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            server.Bind(new IPEndPoint(IPAddress.Parse("192.168.6.41"),8001));//绑定端口号和IP
            Thread threadReceiveMsg=new Thread(ReceiveMsg); //开启接收消息线程
            threadReceiveMsg.Start();
            Thread threadSendMsg = new Thread(sendMsg);//开启发送消息线程
            threadSendMsg.Start();
            Console.WriteLine("服务端已开启");
        }
        /// <summary>
        /// 向指定IP的主机端口发送数据报
        /// </summary>
        static void sendMsg() {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.6.41"),8000);
            while (true)
            {
                string msg = Console.ReadLine();
                server.SendTo(Encoding.UTF8.GetBytes(msg),point);
            }
        }
        /// <summary>
        /// 接收发送给本机IP对应端口号的数据报
        /// </summary>
        static void ReceiveMsg() {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any,0);//用来保存发送方的IP和端口号
                byte[] buffer=new byte[1024];
                int length = server.ReceiveFrom(buffer,ref point);//接收数据报
                string message=Encoding.UTF8.GetString(buffer,0,length);
                Console.WriteLine(DateTime.Now.ToString()+"Msg From:"+point.ToString()+":"+message);
            }
        }
    }

你可能感兴趣的:(Socket,TCP/UDP,C#,c#,服务器,网络)