旗下导航:搜·么
当前位置:网站首页 > .Net教程 > 正文

C# Socket 线程【C#.Net教程】,C# ,Socket ,线程

作者:搜教程发布时间:2019-11-27分类:.Net教程浏览:65评论:0


导读:最初的版本是如许的:点击翻开链接。但一向没有调好,所以就征询了一下同事翔哥,末了开端搞定!客户端代码:usingSystem;usingSystem.Col...
最初的版本是如许的:点击翻开链接。但一向没有调好,所以就征询了一下同事翔哥,末了开端搞定!

客户端代码:


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 线程的内容,更多相关内容请关注ki4网(www.ki4.cn)!

标签:C#Socket线程


欢迎 发表评论: