C#局域网下的简单即时通讯案例

来源:互联网 发布:it运维管理 大数据 编辑:程序博客网 时间:2024/06/06 16:26

首先是服务器部分

using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace Server{    class Program    {                public static Socket socket;        static void Main(string[] args)        {                        MyServer myServer = new MyServer();            myServer.StartUp();            while (true)            {                string strSend = Console.ReadLine();                myServer.Send(strSend, socket);            }                              }    }    public class MyServer    {        //本机的IP地址        private string _ip = "192.168.30.19";        //端口号        private int _port = 10000;        //服务器的 套接字        private Socket _server;        //声明一个连接客户端的线程(连接客户端是一个阻塞线程的方法,不能直接放在主线程里,所以要新开一个线程)        private Thread _acceptClientConnectThread;        /// <summary>        /// 启动服务器        /// </summary>        public void StartUp()        {            try            {                //建立套接字  : 寻址方案,套接字类型,协议类型                _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                //配置本地地址                EndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);                _server.Bind(endPoint);                //监听和接受客户端请求(30为接受客户端的数量)                _server.Listen(30);                //开启接受客户端连接的 线程                _acceptClientConnectThread = new Thread(AcceptClientConnect);                _acceptClientConnectThread.Start();                //服务器建立好之后 打印一下                 Console.WriteLine("{0}:{1} StartUp.", _ip, _port);            }            catch (Exception e)            {                Console.WriteLine(e.Message);            }                  }        /// <summary>        /// 接受客户端的连接        /// </summary>        public void AcceptClientConnect()        {            while (true)            {                try                {                    //接受客户端的连接                    Socket clientSocket = _server.Accept();                    //发消息所需参数(可以针对发送消息扩展,此处只是简单对一个固定客户端发送消息)                    Program.socket = clientSocket;                    //获取客户端的网络地址标识                    IPEndPoint clientEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;                    //打印下谁连接上了服务器                    Console.WriteLine(clientEndPoint.Address.ToString() + "连接上了服务器");                    //开一个接受客户端消息的线程                    Thread accrptClientMsg = new Thread(AcceptMsg);                    accrptClientMsg.Start(clientSocket);                }                catch (Exception e)                {                    Console.WriteLine(e.Message);                }                          }               }        /// <summary>        /// 接收客户端消息        /// </summary>               public void AcceptMsg(object obj)        {            //由于线程只能传递object参数,所以此处需要把object强转成Socket            Socket client = obj as Socket;            //声明一个字节数组 用来接收消息            byte[] buffer = new byte[client.ReceiveBufferSize];            //获取客户端的网络地址标识            IPEndPoint clientEndPoint = client.RemoteEndPoint as IPEndPoint;            while (true)            {                //接收消息                int len = client.Receive(buffer);                string str = Encoding.UTF8.GetString(buffer,0,len);                Console.WriteLine(clientEndPoint.Address.ToString()+":"+_port+"说"+str);                           }        }        /// <summary>        /// 发送消息        /// </summary>               public void Send(string str,Socket client)        {            byte[] strByteArr = Encoding.UTF8.GetBytes(str);            client.Send(strByteArr);        }    }}

下面是客户端部分

using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace Client{    class Program    {        static void Main(string[] args)        {            MyClient myClient = new MyClient();            myClient.StarUp();            while (true)            {                string str = Console.ReadLine();                myClient.Send(str);            }        }    }    public class MyClient    {        //客户端的套接字        private Socket _client;        //接收服务器消息的线程        private Thread _acceptServerMsg;        /// <summary>        /// 启动客户端        /// </summary>        public void StarUp()        {            //建立套接字            _client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);            //连接到服务器            _client.Connect("192.168.30.19",10000);            //开启接收消息的线程            _acceptServerMsg = new Thread(AcceptServerMsg);            _acceptServerMsg.Start();        }        /// <summary>        /// 接收服务器的消息        /// </summary>        public void AcceptServerMsg()        {            //声明一个接收消息的字节数组            byte[] buffer = new byte[1024 * 64];            while (true)            {                try                {                    //接收消息                    int len = _client.Receive(buffer);                    string str = Encoding.UTF8.GetString(buffer,0,len);                    Console.WriteLine(str);                }                catch (Exception e)                {                    Console.WriteLine(e);                }            }        }        /// <summary>        /// 发消息        /// </summary>                public void Send(string str)        {            byte[] buffer = Encoding.UTF8.GetBytes(str);            _client.Send(buffer);        }    }}

以上就是可以在局域网下执行的 简单的即时通讯 的案例
其中可以根据个人需要对发送信息的方式进行一些扩展。

原创粉丝点击