• C#实现局域网聊天 通讯 Socket TCP 多人


    程序分别为服务端与客户端,服务端创建套接字使用多线程侦听多客户端请求

    代码需要引用System.Net;和System.Net.Socket;这两个类

    分享源码demo:https://pan.baidu.com/s/10RuE9Vk0cIoxY91uzx4Gig     提取码:4eds

    运行图:

    服务端

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace ConsoleServer
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             ServerControl Server = new ServerControl();//初始化Socket
    13             Server.Start();//启动侦听连接
    14             //Console.WriteLine("123");
    15             Console.Read();
    16         }
    17     }
    18 }
    展开查看代码
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Net.Sockets;
     6 using System.Net;
     7 using System.Threading;
     8 
     9 namespace ConsoleServer
    10 {
    11     public class ServerControl
    12     {
    13         public Socket ServerSocket;
    14         public List<Socket> ClientList=null;//客户端集合
    15 
    16         /// <summary>
    17         /// 构造函数
    18         /// </summary>
    19         public ServerControl()
    20         {
    21             //创建套接字,ipv4寻址方式,套接字类型,传输协议
    22             ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    23             ClientList=new List<Socket>();//实例化客户端接入集合介入
    24         }
    25 
    26         public void Start()
    27         {
    28             ServerSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),1231));//绑定IP和端口
    29             ServerSocket.Listen(10000);//支持最多连接数
    30             Console.WriteLine("start server succeed");
    31 
    32             //当有客户接入时当前线程会被挂起,每次新接入客户端创建独立线处理
    33             Thread ThreadAccept = new Thread(Accept);
    34             ThreadAccept.IsBackground = true;//设置为后台线程
    35             ThreadAccept.Start();//启动线程
    36 
    37         }
    38 
    39         private void Accept()
    40         { 
    41             Socket Client = ServerSocket.Accept();//客户端接入当前线程挂起
    42             IPEndPoint point=Client.RemoteEndPoint as IPEndPoint;//将远端节点转为ip和端口
    43             Console.WriteLine("IP {0}:{1} connect succeed",point.Address,point.Port);//显示接入信息
    44             ClientList.Add(Client);//将此连接添加到客户集合
    45 
    46             //接收消息只处理一次,线程被挂起,创建新线程处理其新消息
    47             Thread ThreadReceive = new Thread(Receive);
    48             ThreadReceive.IsBackground = true;//设置为后台线程
    49             ThreadReceive.Start(Client);//启动线程
    50             Accept();//回掉处理新接入客户端
    51         }
    52 
    53         /// <summary>
    54         /// 处理收到的消息
    55         /// </summary>
    56         /// <param name="obj"></param>
    57         private void Receive(object obj)
    58         {
    59             Socket Client = obj as Socket;
    60             IPEndPoint point = Client.RemoteEndPoint as IPEndPoint;//将远端节点转为ip和端口
    61             try
    62             {
    63                 byte[] ByteReceive = new byte[1024];//消息数组
    64                 int ReceiveLenght = Client.Receive(ByteReceive);//只处理一次消息,此处会被挂起
    65                 string msg = point.Address + "[" + point.Port + "]:" + Encoding.UTF8.GetString(ByteReceive, 0, ReceiveLenght);
    66                 Console.WriteLine(msg);//打印收到的消息
    67                 Broadcast(Client, msg);//广播消息
    68       
    69                 Client.Send(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));//回发当前时间给消息源
    70                 Receive(Client);//回调处理新消息
    71             }
    72             catch
    73             {
    74                 ClientList.Remove(Client);//当客户端断开,从客户端集合移除该客户端
    75                 Console.WriteLine("{0}[{1}]:断开连接", point.Address, point);//打印提示信息
    76             }
    77 
    78         }
    79 
    80         /// <summary>
    81         /// 广播消息
    82         /// </summary>
    83         /// <param name="cli"></param>
    84         /// <param name="msg"></param>
    85         public void Broadcast(Socket cli,string msg)
    86         {
    87             foreach (var  item in ClientList )//遍历所有客户端
    88             {
    89                 if (item != cli)
    90                     item.Send(Encoding.UTF8.GetBytes(msg));//给除数据源以外客户端发送广播消息
    91             }
    92         }
    93     }
    94 }
    展开查看代码

    客户端

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace ConsoleClient
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             ClientControl Client = new ClientControl();//初始化Socket
    13             Client.Connect("127.0.0.1",1231);//连接到服务器
    14             Console.WriteLine("Please enter the content to send,Enter exit to exit!");//提示信息
    15             string msg=Console.ReadLine();//输入
    16             while (msg!="exit")//判断是否退出
    17             {
    18                 Client.Send(msg);//发送消息
    19                 msg = Console.ReadLine();//输入消息
    20 
    21             }
    22             
    23         }
    24     }
    25 }
    展开查看代码
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Net.Sockets;
     6 using System.Threading;
     7 
     8 namespace ConsoleClient
     9 {
    10     public class ClientControl
    11     {
    12         private Socket ClientSocket;
    13 
    14         public ClientControl()
    15         {
    16             //创建套接字,ipv4寻址方式,套接字类型,传输协议
    17             ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    18         }
    19 
    20         /// <summary>
    21         /// 连接到服务器
    22         /// </summary>
    23         /// <param name="IP"></param>
    24         /// <param name="Port"></param>
    25         public void Connect(string IP, Int32 Port)
    26         {
    27             try
    28             {
    29                 ClientSocket.Connect(IP, Port);//连接到指定服务器
    30                 Console.WriteLine("connect server succeed ok!");//提示信息
    31                 //收到消息是线程会被挂起,创建新线程处理收到的消息
    32                 Thread ThreadReceive = new Thread(Receive);
    33                 ThreadReceive.IsBackground = true;
    34                 ThreadReceive.Start();
    35             }
    36             catch(SocketException e)
    37             {
    38                 Console.WriteLine("无法连接到{0}:{1}{2}",IP,Port,e);
    39             }
    40         }
    41 
    42         /// <summary>
    43         /// 发送消息
    44         /// </summary>
    45         /// <param name="msg"></param>
    46         public void Send(string msg)
    47         { 
    48             ClientSocket.Send(Encoding.UTF8.GetBytes(msg));
    49         }
    50 
    51         /// <summary>
    52         /// 接收消息
    53         /// </summary>
    54         private void Receive()
    55         {
    56             try
    57             {
    58                 byte[] ByteReceive = new byte[1024];
    59                 int ReceiveLenght = ClientSocket.Receive(ByteReceive);//此处线程会被挂起
    60                 Console.WriteLine("{0}", Encoding.UTF8.GetString(ByteReceive, 0, ReceiveLenght));
    61                 Receive();
    62             }
    63             catch 
    64             {
    65                 Console.WriteLine("服务器已断开");
    66             }
    67         }
    68     }
    69 }
    展开查看代码
  • 相关阅读:
    SQL 连接
    nvl() 数值替换函数 oracle使用
    Oracle 中sql语句中的取前n条数据
    设置序列
    Oracle创建用户 创建表空间 分配权限
    oracle11 刚刚安装后提示invalid username password logon denied
    关于index 索引
    事物
    数据库 oracle 设计三范式
    TXT编写程序-编译-执行流程
  • 原文地址:https://www.cnblogs.com/xwcs/p/12901859.html
Copyright © 2020-2023  润新知