C#使用Socket實現一個socket服務器與多個socket客戶端通訊

  筆記一下知識內容,原文地址:https://www.cnblogs.com/yy3b2007com/p/7476458.htmlhtml

  server端代碼數組

 

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

namespace SocketServerAcceptMultipleClient
{
    public class SocketServer
    {
        // 建立一個和客戶端通訊的套接字
        static Socket socketwatch = null;
        //定義一個集合,存儲客戶端信息
        static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

        public static void Main(string[] args)
        {
            //定義一個套接字用於監聽客戶端發來的消息,包含三個參數(IP4尋址協議,流式鏈接,Tcp協議)  
            socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服務端發送信息須要一個IP地址和端口號  
            IPAddress address = IPAddress.Parse("127.0.0.1");
            //將IP地址和端口號綁定到網絡節點point上  
            IPEndPoint point = new IPEndPoint(address, 8098);
            //此端口專門用來監聽的  

            //監聽綁定的網絡節點  
            socketwatch.Bind(point);

            //將套接字的監聽隊列長度限制爲20  
            socketwatch.Listen(20);

            //負責監聽客戶端的線程:建立一個監聽線程  
            Thread threadwatch = new Thread(watchconnecting);

            //將窗體線程設置爲與後臺同步,隨着主線程結束而結束  
            threadwatch.IsBackground = true;

            //啓動線程     
            threadwatch.Start();

            Console.WriteLine("開啓監聽。。。");
            Console.WriteLine("點擊輸入任意數據回車退出程序。。。");
            Console.ReadKey();
            Console.WriteLine("退出監聽,並關閉程序。");
        }

        //監聽客戶端發來的請求  
        static void watchconnecting()
        {
            Socket connection = null;

            //持續不斷監聽客戶端發來的請求     
            while (true)
            {
                try
                {
                    connection = socketwatch.Accept();
                }
                catch (Exception ex)
                {
                    //提示套接字監聽異常     
                    Console.WriteLine(ex.Message);
                    break;
                }

                //獲取客戶端的IP和端口號  
                IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                //讓客戶顯示"鏈接成功的"的信息  
                string sendmsg = "鏈接服務端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
                byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                connection.Send(arrSendMsg);

                //客戶端網絡結點號  
                string remoteEndPoint = connection.RemoteEndPoint.ToString();
                //顯示與客戶端鏈接狀況
                Console.WriteLine("成功與" + remoteEndPoint + "客戶端創建鏈接!\t\n");
                //添加客戶端信息  
                clientConnectionItems.Add(remoteEndPoint, connection);

                //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); 
                IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

                //建立一個通訊線程      
                ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
                Thread thread = new Thread(pts);
                //設置爲後臺線程,隨着主線程退出而退出 
                thread.IsBackground = true;
                //啓動線程     
                thread.Start(connection);
            }
        }

        /// <summary>
        /// 接收客戶端發來的信息,客戶端套接字對象
        /// </summary>
        /// <param name="socketclientpara"></param>    
        static void recv(object socketclientpara)
        {
            Socket socketServer = socketclientpara as Socket;

            while (true)
            {
                //建立一個內存緩衝區,其大小爲1024*1024字節  即1M     
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //將接收到的信息存入到內存緩衝區,並返回其字節數組的長度    
                try
                {
                    int length = socketServer.Receive(arrServerRecMsg);

                    //將機器接受到的字節數組轉換爲人能夠讀懂的字符串     
                    string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

                    //將發送的字符串信息附加到文本框txtMsg上     
                    Console.WriteLine("客戶端:" + socketServer.RemoteEndPoint + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n");

                    socketServer.Send(Encoding.UTF8.GetBytes("測試server 是否能夠發送數據給client "));
                }
                catch (Exception ex)
                {
                    clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

                    Console.WriteLine("Client Count:" + clientConnectionItems.Count);

                    //提示套接字監聽異常  
                    Console.WriteLine("客戶端" + socketServer.RemoteEndPoint + "已經中斷鏈接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
                    //關閉以前accept出來的和客戶端進行通訊的套接字 
                    socketServer.Close();
                    break;
                }
            }
        }

        ///      
        /// 獲取當前系統時間的方法    
        /// 當前時間     
        static DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
    }
}

  client端代碼服務器

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace SocketClient
{
    public partial class Main : Form
    {
        //建立 1個客戶端套接字 和1個負責監聽服務端請求的線程  
        Thread threadclient = null;
        Socket socketclient = null;

        public Main()
        {
            InitializeComponent();

            StartPosition = FormStartPosition.CenterScreen;
            //關閉對文本框的非法線程操做檢查  
            TextBox.CheckForIllegalCrossThreadCalls = false;

            this.btnSendMessage.Enabled = false;
            this.btnSendMessage.Visible = false;

            this.txtMessage.Visible = false;
        }

        private void btnConnection_Click(object sender, EventArgs e)
        {
            this.btnConnection.Enabled = false;
            //定義一個套接字監聽  
            socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //獲取文本框中的IP地址  
            IPAddress address = IPAddress.Parse("127.0.0.1");

            //將獲取的IP地址和端口號綁定在網絡節點上  
            IPEndPoint point = new IPEndPoint(address, 8098);

            try
            {
                //客戶端套接字鏈接到網絡節點上,用的是Connect  
                socketclient.Connect(point);
                this.btnSendMessage.Enabled = true;
                this.btnSendMessage.Visible = true;
                this.txtMessage.Visible = true;
            }
            catch (Exception)
            {
                Debug.WriteLine("鏈接失敗\r\n");

                this.txtDebugInfo.AppendText("鏈接失敗\r\n");
                return;
            }

            threadclient = new Thread(recv);
            threadclient.IsBackground = true;
            threadclient.Start();
        }

        // 接收服務端發來信息的方法    
        void recv()
        {
            int x = 0;
            //持續監聽服務端發來的消息 
            while (true)
            {
                try
                {
                    //定義一個1M的內存緩衝區,用於臨時性存儲接收到的消息  
                    byte[] arrRecvmsg = new byte[1024 * 1024];

                    //將客戶端套接字接收到的數據存入內存緩衝區,並獲取長度  
                    int length = socketclient.Receive(arrRecvmsg);

                    //將套接字獲取到的字符數組轉換爲人能夠看懂的字符串  
                    string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
                    if (x == 1)
                    {
                        this.txtDebugInfo.AppendText("服務器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
                        Debug.WriteLine("服務器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
                    }
                    else
                    {
                        this.txtDebugInfo.AppendText(strRevMsg + "\r\n\n");
                        Debug.WriteLine(strRevMsg + "\r\n\n");
                        x = 1;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("遠程服務器已經中斷鏈接" + "\r\n\n");
                    Debug.WriteLine("遠程服務器已經中斷鏈接" + "\r\n");
                    break;
                }
            }
        }

        //獲取當前系統時間  
        DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }

        //發送字符信息到服務端的方法  
        void ClientSendMsg(string sendMsg)
        {
            //將輸入的內容字符串轉換爲機器能夠識別的字節數組     
            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            //調用客戶端套接字發送字節數組     
            socketclient.Send(arrClientSendMsg);
            //將發送的信息追加到聊天內容文本框中     
            Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
            this.txtDebugInfo.AppendText("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            //調用ClientSendMsg方法 將文本框中輸入的信息發送給服務端     
            ClientSendMsg(this.txtMessage.Text.Trim());
            this.txtMessage.Clear();
        }
    }
}
相關文章
相關標籤/搜索