C# socket通信实现两个控制台之间聊天

2021-11-03 09:49:10 浏览数 (1)

1、运行效果

图1 启动服务端

图2 启动客户端

图3 客户发消息

图4 服务端发消息

图5 客户主动关闭,服务段打印异常详情

2、服务器端源码

服务端和客户端都要添加一下namespace:

using System.Net;

using System.Net.Sockets;

using System.Threading;

源码:

代码语言:javascript复制
 class Program
    {
        private static string serverIP = "192.168.3.42";//本机ip地址
        private static int serverPort = 8888;
        private static int bufferSize = 1024;
        private static int count = 0;//表示对话序号

        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse(serverIP);
            IPEndPoint ipe = new IPEndPoint(ip, serverPort);
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                s.Bind(ipe);
                s.Listen(10);
                Console.WriteLine("等待连接……");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Thread mainTrd = new Thread(Run);
            mainTrd.Start(s);
        }
        /// <summary>
        /// 启动服务器的socket。
        /// 此处要想修改为多用户连接,对每个新用户都new一个RecMsg线程,并且Dictionary<T1,T2>存储每一对ipe和socket即可
        /// </summary>
        /// <param name="o">传入的socket对象</param>
        private static void Run(object o)
        {
            Socket socket = o as Socket;
            try
            {               
                Socket connSocket = socket.Accept();
                //客户和服务器连接成功。
                Console.WriteLine("{0}成功连接到本机。", connSocket.RemoteEndPoint);
                //接下来的事情交给会话线程
                Thread recTh = new Thread(RecMsg);
                recTh.Start(connSocket);
                Thread sendTh = new Thread(SendMsg);
                sendTh.Start(connSocket);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
        private static void RecMsg(object o)
        {
            Socket connSocket = o as Socket;
            while (true)
            {
                byte[] buffer = new Byte[bufferSize];
                try
                {
                    int length = connSocket.Receive(buffer);
                    byte[] realBuffer = new Byte[length];
                    Array.Copy(buffer, 0, realBuffer, 0, length);
                    string str = System.Text.Encoding.Default.GetString(realBuffer);
                    Console.Write("[{0}] ", count  );
                    Console.WriteLine("{0}说:{1}.", connSocket.RemoteEndPoint, str);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.ReadKey();
                    break;
                }                            
            }
        }
        private static void SendMsg(object o) 
        {
            Socket connSocket = o as Socket;
            while (true)
            {
                string str = Console.ReadLine();
                if (str != string.Empty)
                {
                    byte[] buffer = Encoding.Default.GetBytes(str);
                    connSocket.Send(buffer, buffer.Length, SocketFlags.None);
                }               
            }
        }
    }

3、客户端源码

代码语言:javascript复制
class Program
    {
        private static string host = "192.168.3.42";
        private static int port = 8888;
        private static int bufferSize = 1024;
        static IPAddress ip = IPAddress.Parse(host);
        static IPEndPoint ipe = new IPEndPoint(ip, port);
        private static int count = 0;//表示对话序号
        static void Main(string[] args)
        {            
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                s.Connect(ipe);
                Console.WriteLine("成功连接到{0}。", s.RemoteEndPoint);
                Console.WriteLine("请输入要发送给服务器的话,按Enter发送。");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
            Thread clientTh = new Thread(SendToServer);
            clientTh.Start(s);
            Thread recTh = new Thread(RecMsg);
            recTh.Start(s);            
        }
        private static void RecMsg(object o)
        {
            Socket connSocket = o as Socket;
            while (true)
            {
                byte[] buffer = new Byte[bufferSize];
                try
                {
                    int length = connSocket.Receive(buffer);
                    byte[] realBuffer = new Byte[length];
                    Array.Copy(buffer, 0, realBuffer, 0, length);
                    string str = System.Text.Encoding.Default.GetString(realBuffer);
                    Console.Write("[{0}] ", count  );
                    Console.WriteLine("{0}说:{1}.", connSocket.RemoteEndPoint, str);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.ReadKey();
                    break;
                }
            }
        }
        private static void SendToServer(object o)
        {            
            Socket socket = o as Socket;            
            while (true)
            {
                try
                {
                    string str = Console.ReadLine();                    
                    if (str != string.Empty)
                    {
                        byte[] bt = Encoding.Default.GetBytes(str);
                        socket.Send(bt, bt.Length, 0);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发送失败。");
                    Debug.WriteLine(ex);
                    throw;
                }
            }                     
        }
    }

0 人点赞