C# Socket案例(服務端與客戶端)

原文鏈接:https://blog.csdn.net/qq_42203978/article/details/80520299

本文鏈接:https://blog.csdn.net/qq_42203978/article/details/80520299
服務端完整代碼

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
 
namespace ServerSocket
{
    public partial class Form1 : Form
    {
        //定義Socket對象
        Socket serverSocket;
        //定義監聽線程
        Thread listenThread;
        //定義接收客戶端數據線程
        Thread threadReceive;
        //定義雙方通信
        Socket socket;
        string str;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.text_ip.Text.Trim());
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                //綁定ip和端口
                serverSocket.Bind(new IPEndPoint(ip, Convert.ToInt32(this.text_port.Text.Trim())));
                //設置最多10個排隊連接請求
                serverSocket.Listen(10);
                //開啓線程循環監聽
                listenThread = new Thread(ListenClientConnect);
                listenThread.Start();
                this.button_start.Enabled = false;
                
            } catch {
                MessageBox.Show("監聽異常", "監聽異常");
            }
            
        }
 
        //監聽
        private void ListenClientConnect()
        {
            while (true) {
                //監聽到客戶端的連接,獲取雙方通信socket
                socket = serverSocket.Accept();
                //創建線程循環接收客戶端發送的數據
                threadReceive = new Thread(Receive);
                //傳入雙方通信socket
                threadReceive.Start(socket);
            }
        }
 
        //接收客戶端數據
        private void Receive(object socket)
        {
            try {
                Socket myClientSocket = (Socket)socket;
                while (true) {
                    byte[] buff = new byte[20000];
                    int r = myClientSocket.Receive(buff);
                    str = Encoding.Default.GetString(buff, 0, r);                  
                    this.Invoke(new Action(() => { this.text_log1.Text = str; }));
                }
            } catch {
                MessageBox.Show("接收數據失敗", "接收數據失敗");
            }
        }
 
        //關閉
        private void button_close_Click(object sender, EventArgs e)
        {
            //socket關閉
            serverSocket.Close();
            //線程關閉
            listenThread.Abort();
            threadReceive.Abort();
        }
 
        //發送
        private void button_send_Click(object sender, EventArgs e)
        {
            try
            {
                string strMsg = this.text_log2.Text.Trim();
                byte[] buffer = new byte[20000];
                buffer = Encoding.Default.GetBytes(strMsg);
                socket.Send(buffer);
            }
            catch
            {
                MessageBox.Show("發送數據失敗", "發送數據失敗");
            }
        }
    }
}
客戶端完整代碼

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
 
namespace ClientSocket
{
    public partial class Form1 : Form
    {
        //定義Socket對象
        Socket clientSocket;
        //創建接收消息的線程
        Thread threadReceive;
        //接收服務端發送的數據
        string str;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
 
        private void button_connect_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.text_ip.Text.Trim());
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                //連接服務端
                clientSocket.Connect(ip, Convert.ToInt32(this.text_port.Text.Trim()));
                //開啓線程不停的接收服務端發送的數據
                threadReceive = new Thread(new ThreadStart(Receive));
                threadReceive.IsBackground = true;
                threadReceive.Start();
                //設置連接按鈕在連接服務端後狀態爲不可點
                this.button_connect.Enabled = false;
            } catch {
                MessageBox.Show("連接服務端失敗,請確認ip和端口是否填寫正確", "連接服務端失敗");
            }
        }
 
        //接收服務端消息的線程方法
        private void Receive()
        {
            try {
                while (true) {
                    byte[] buff = new byte[20000];
                    int r = clientSocket.Receive(buff);
                    str = Encoding.Default.GetString(buff,0,r);
                    this.Invoke(new Action(() => { this.text_log1.Text = str; }));
                }
            } catch {
                MessageBox.Show("獲取服務端參數失敗","獲取服務端參數失敗");
            }
        }
 
        private void button_close_Click(object sender, EventArgs e)
        {
            //clientSocket關閉
            clientSocket.Close();
            //threadReceive關閉
            threadReceive.Abort();
        }
 
        private void button_send_Click(object sender, EventArgs e)
        {
            try {
                string strMsg = this.text_log2.Text.Trim();
                byte[] buffer = new byte[20000];
                buffer = Encoding.Default.GetBytes(strMsg);
                clientSocket.Send(buffer);
            } catch {
                MessageBox.Show("發送數據失敗", "發送數據失敗");
            }
        }
    }
}
編譯成功後點擊發送效果圖

具體步驟(思路)

服務器端:
第一步:創建一個用於監聽連接的Socket對像;
第二步:用指定的端口號和服務器的ip建立一個EndPoint對像;
第三步:用socket對像的Bind()方法綁定EndPoint;
第四步:用socket對像的Listen()方法開始監聽;

第五步:接收到客戶端的連接,用socket對像的Accept()方法創建一個新的用於和客戶端進行通信的socket對像;

第六步:通信結束後一定記得關閉socket;

 

客戶端:
第一步:建立一個Socket對像;
第二步:用指定的端口號和服務器的ip建立一個EndPoint對像;
第三步:用socket對像的Connect()方法以上面建立的EndPoint對像做爲參數,向服務器發出連接請求;
第四步:如果連接成功,就用socket對像的Send()方法向服務器發送信息;
第五步:用socket對像的Receive()方法接受服務器發來的信息 ;

 

第六步:通信結束後一定記得關閉socket;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章