首頁 後端開發 C#.Net教程 C# Socket 線程

C# Socket 線程

Feb 20, 2017 am 11:06 AM

最初的版本是這樣的:點擊開啟連結。但一直沒有調好,所以我諮詢了一下同事翔哥,最後初步搞定!

客戶端程式碼:


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.Net.Sockets;
using System.Threading;
using System.Net;
using System.Diagnostics;

namespace SocketClient
{
    public partial class Client : Form
    {    
        Socket vsServerSocket;
        Thread vsClientThread;
        string strIP = "127.0.0.1";
        public delegate void PassString(string strMsg);
        int nPort = 9001;
        public Client()
        {
            InitializeComponent();
        }
        public void SetSendData(string strMsg)
        {
            if (tBoxClientSend.InvokeRequired == true)
            {
                PassString d = new PassString(SetSendData);
                this.Invoke(d, new object[] { strMsg });
            }
            else
            {
                tBoxClientSend.Text = strMsg;
            }
        }
        public void SetRecvData(string strMsg)
        {
            if (tBoxClientReceive.InvokeRequired == true)
            {
                PassString d = new PassString(SetRecvData);
                this.Invoke(d, new object[] { strMsg });
            }
            else
            {
                tBoxClientReceive.Text = strMsg;
            }
        }
        private void ClientHandle()
        {
            string strRecv = string.Empty;
            //IPEndPoint其实就是一个IP地址和端口的绑定,可以代表一个服务,用来Socket通讯。
            //IPAddress类中有一个 Parse()方法,可以把点分的十进制IP表示转化成IPAddress类
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort);
            //创建套接字实例
            //这里创建的时候用ProtocolType.Tcp,表示建立一个面向连接(TCP)的Socket
            vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //将所创建的套接字与IPEndPoint绑定
                vsServerSocket.Bind(ipep);
            }
            catch (SocketException ex)
            {
                MessageBox.Show("Connect Error: " + ex.Message);
                return;
            }
            Byte[] buffer = new Byte[1024];
            //设置套接字为收听模式
            vsServerSocket.Listen(10);
            //循环监听   
            while (true)
            {
                //接收服务器信息
                int bufLen = 0;               
                try
                {
                    Socket vsClientSocket = vsServerSocket.Accept();
                    bufLen=vsClientSocket.Receive(buffer);
                    vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None);
                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Receive Error:" + ex.Message);                   
                }
                strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen);
                SetRecvData(strRecv);                
                //vsClientSocket.Shutdown(SocketShutdown.Both);
                //vsClientSocket.Close();
            }
        }

        //发送数据
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            string ss = tBoxClientSend.Text;
            Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9002);
            centerClient.Connect(GsServer);
            centerClient.Send(Encoding.ASCII.GetBytes(ss));
            centerClient.Close();
        }

        private void Client_Load(object sender, EventArgs e)
        {
            //连接服务器
            //通过ThreadStart委托告诉子线程讲执行什么方法
            vsClientThread = new Thread(new ThreadStart(ClientHandle));
            vsClientThread.Start();
        }
        //窗体关闭时杀死客户端进程
        private void Client_FormClosing(object sender, FormClosingEventArgs e)
        {
            KillProcess();
        }
        //杀死客户端进程
        private void KillProcess()
        {
            Process[] processes = Process.GetProcessesByName("SocketClient");
            foreach (Process process in processes)
            {
                process.Kill();
                break;
            }
        }
    }
}
登入後複製

服務端程式碼:



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 SocketServer
{
    public partial class Server : Form
    {
        Thread vsServerThread;
        Socket vsServerSocket;      
        string strIP = "127.0.0.1";
        public delegate void PassString(string strMsg);     
        int nPort = 9002;
        public Server()
        {
            InitializeComponent();
        }
        private void SeverSendData(string strMsg)
        {
            //Control.InvokeRequired 属性,命名空间:  System.Windows.Forms
            //获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。
            if (tBoxServerSend.InvokeRequired == true)
            {
                //Control.Invoke 方法 (Delegate)
                //在拥有此控件的基础窗口句柄的线程上执行指定的委托。
                PassString d = new PassString(SeverSendData);
                this.Invoke(d, new object[] { strMsg });
            }
            else
            {
                tBoxServerSend.Text = strMsg;
            }
        }
        private void SeverRecvData(string strMsg)
        {
            if (tBoxServerReceive.InvokeRequired == true)
            {
                PassString d = new PassString(SeverRecvData);
                this.Invoke(d, new object[] { strMsg });
            }
            else
            {
                tBoxServerReceive.Text = strMsg;
            }
        }       
        private void ServerStart()
        {
            string strRecv = string.Empty;
            //创建IPEndPoint实例
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort);
            //创建一个套接字
            vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //将所创建的套接字与IPEndPoint绑定
            try
            {
                vsServerSocket.Bind(ipep);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString());
                return;
            }
            //设置套接字为收听模式
            vsServerSocket.Listen(10);
            int bufLen = 0;
            //循环监听  
            while (true)
            {
                //在套接字上接收接入的连接
                Socket vsClientSocket = vsServerSocket.Accept();     
                try
                {                                  
                    Byte[] buffer = new Byte[1024];
                    //在套接字上接收客户端发送的信息
                    bufLen = vsClientSocket.Receive(buffer);
                    vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None);
                    if (bufLen == 0)
                        continue;   
                    //将指定字节数组中的一个字节序列解码为一个字符串。
                    strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen);
                    SeverRecvData(strRecv.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Listening Error: " + ex.Message);
                    vsClientSocket.Close();
                    vsServerSocket.Close();
                }
            }
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            string ss = tBoxServerSend.Text;
            Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
            centerClient.Connect(GsServer);
            centerClient.Send(Encoding.ASCII.GetBytes(ss));
            centerClient.Send(Encoding.ASCII.GetBytes(ss));
            //Thread.Sleep(100);
            //centerClient.Close();
        }
        private void Server_Load(object sender, EventArgs e)
        {
            vsServerThread = new Thread(new ThreadStart(ServerStart));
            vsServerThread.Start();
        }
        //窗体关闭时杀死客户端进程
        private void Server_FormClosing(object sender, FormClosingEventArgs e)
        {
            KillProcess();
        }
        //杀死客户端进程
        private void KillProcess()
        {
            Process[] processes = Process.GetProcessesByName("Server");
            foreach (Process process in processes)
            {
                process.Kill();
                break;
            }
        }
    }
}
登入後複製


效果如下:

客戶端可以傳送訊息給服務端,服務端也可以傳送訊息給客戶端。

缺點:

現在服務端只能連接一個客戶端

以上就是C#  Socket  線程的內容,更多相關內容請關注PHP中文網(www.php.cn)!


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

使用 C# 的活動目錄 使用 C# 的活動目錄 Sep 03, 2024 pm 03:33 PM

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

C# 序列化 C# 序列化 Sep 03, 2024 pm 03:30 PM

C# 序列化指南。這裡我們分別討論C#序列化物件的介紹、步驟、工作原理和範例。

C# 中的隨機數產生器 C# 中的隨機數產生器 Sep 03, 2024 pm 03:34 PM

C# 隨機數產生器指南。在這裡,我們討論隨機數產生器的工作原理、偽隨機數和安全數的概念。

C# 資料網格視圖 C# 資料網格視圖 Sep 03, 2024 pm 03:32 PM

C# 資料網格視圖指南。在這裡,我們討論如何從 SQL 資料庫或 Excel 檔案載入和匯出資料網格視圖的範例。

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 模式指南。在這裡,我們討論 C# 中模式的介紹和前 3 種類型,以及其範例和程式碼實作。

C# 中的階乘 C# 中的階乘 Sep 03, 2024 pm 03:34 PM

C# 階乘指南。這裡我們討論 C# 中階乘的介紹以及不同的範例和程式碼實作。

C# 中的質數 C# 中的質數 Sep 03, 2024 pm 03:35 PM

C# 質數指南。這裡我們討論c#中素數的介紹和範例以及程式碼實作。

c#多線程和異步的區別 c#多線程和異步的區別 Apr 03, 2025 pm 02:57 PM

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。

See all articles