程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Socket協議通訊,socket協議

Socket協議通訊,socket協議

編輯:C#入門知識

Socket協議通訊,socket協議


服務器端代碼:

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

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public List<Socket> serverSockeList = new List<Socket>();
        Socket serverSocke = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        bool kg=true;
        string recStr = "";
        byte[] recByte = new byte[1000];
        int bytes = 0;
        delegate void invokeInfo(string obj);
        private void But_Starlisten_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txt_IP.Text) || string.IsNullOrEmpty(txt_port.Text))
                    return;
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(txt_IP.Text), int.Parse(txt_port.Text));
                serverSocke.Bind(ipe);
                serverSocke.Listen(10000);
                txt_MessageLog.Text += "監聽已經打開,請等待\r\n";

                Thread conn = new Thread(new ParameterizedThreadStart(GetALLClientConn));
                conn.IsBackground = true;
                conn.Start(serverSocke);
            }
            catch (Exception ex)
            {
                txt_MessageLog.Text += "服務異常\r\n";
            }
        }

        /// <summary>
        /// 關閉所有的Socket協議和線程
        /// </summary>
        public void Close()
        {
            try
            {
                kg = false;
                foreach (var item in serverSockeList)
                {
                    if (item.Connected)
                        item.Shutdown(SocketShutdown.Both);
                    if (item != null)
                        item.Close();
                }
                if (serverSocke.Connected)
                    serverSocke.Shutdown(SocketShutdown.Both);
                if (serverSocke != null)
                    serverSocke.Close();
            }
            catch {
                txt_MessageLog.Text += "服務器連接關閉\r\n";
            }
        }

        /// <summary>
        /// 獲取所有客戶端連接
        /// </summary>
        /// <param name="obj">客戶端Socket對象</param>
        public void GetALLClientConn(object obj)
        {
            Socket serverSocke = obj as Socket;
            try
            {
                while (kg)
                {
                    Socket newSocket = serverSocke.Accept();
                    serverSockeList.Add(newSocket);
                    txt_MessageLog.Invoke(new invokeInfo(Output), newSocket.RemoteEndPoint + "連接已經建立");
                    Thread t = new Thread(new ParameterizedThreadStart(GetInfo));
                    t.IsBackground = true;
                    t.Start(newSocket);
                }
            }
            catch {
                txt_MessageLog.Invoke(new invokeInfo(Output), "服務器異常");
               
            }
        }

        
        /// <summary>
        /// 獲取該Socket對象的信息
        /// </summary>
        /// <param name="newSocket">Socket對象</param>
        public void GetInfo(object obj)
        {
            Socket newSocket = obj as Socket;
            try
            {
                while (kg)
                {
                   
                    bytes = newSocket.Receive(recByte, recByte.Length, SocketFlags.None);

                    if (bytes <= 0)
                    {
                        txt_MessageLog.Invoke(new invokeInfo(Output), newSocket.RemoteEndPoint + "連接已斷開");
                        serverSockeList.Remove(newSocket);
                        if (newSocket.Connected)
                            newSocket.Shutdown(SocketShutdown.Both);
                        newSocket.Disconnect(false);
                        newSocket.Close();
                        break;
                    }
                    recStr = Encoding.UTF8.GetString(recByte, 0, bytes);
                    txt_MessageLog.Invoke(new invokeInfo(Output), recStr);
                    byte[] sendBytes = Encoding.UTF8.GetBytes(recStr);
                    foreach (var item in serverSockeList)
                    {
                        if (item != newSocket)
                            item.Send(sendBytes);
                    }
                }
            }
            catch (Exception ex)
            {
                txt_MessageLog.Invoke(new invokeInfo(Output), newSocket.RemoteEndPoint + "的信息接收異常");
            }
        }

        public void Output(string info)
        {
            txt_MessageLog.Text += info + "\r\n";
        }

        //發送信息
        private void But_Send_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txt_Send.Text))
                    return;
                string sendStr = txt_Send.Text;
                txt_Send.Text = "";
                txt_MessageLog.Text += "服務端信息:" + sendStr + "\r\n";
                byte[] sendBytes = Encoding.UTF8.GetBytes("服務端信息:" + sendStr);
                Socket error = null;
                foreach (var item in serverSockeList)
                {
                    if (item.Poll(-1,SelectMode.SelectWrite))
                        item.Send(sendBytes);
                    else
                        error = item;
                }
                if (error != null)
                    serverSockeList.Remove(error);
            }
            catch (Exception ex)
            {
                txt_MessageLog.Text += "服務端發送信息異常\r\n";
            }
        }

        private void But_endlisten_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Close();
        }
    }
}

服務器端界面:

 

 

------------------------------------------------------------------------------------------

 

 

客戶端代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Socket clientSocket;
        bool kg = true;
        delegate void invokeInfo(string obj);
        string recStr = "";
        byte[] recBytes = new byte[4096];
        int bytes = 0;
        public void Output(string info)
        {
            txt_MessageLog.Text += info + "\r\n";
        }

        private void But_Send_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txt_Send.Text))
                    return;
                string sendStr = txt_Send.Text;
                txt_Send.Text = "";
                txt_MessageLog.Text += "我:" + sendStr + "\r\n";
                byte[] sendBytes = Encoding.UTF8.GetBytes(clientSocket.RemoteEndPoint + ":" + sendStr);
                int i= clientSocket.Send(sendBytes);
            }
            catch (Exception ex)
            {
                txt_MessageLog.Text += "信息發送異常\r\n";
            }
        }

        private void But_Starlisten_Click(object sender, EventArgs e)
        {
            try
            {
               
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (string.IsNullOrEmpty(txt_IP.Text) || string.IsNullOrEmpty(txt_port.Text))
                    return;
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(txt_IP.Text), int.Parse(txt_port.Text));
                clientSocket.Connect(ipe);
                txt_MessageLog.Text += "連接成功\r\n";
                groupBox1.Text += txt_IP.Text;
                Thread t = new Thread(new ParameterizedThreadStart(GetInfo));
                t.IsBackground = true;
                t.Start(clientSocket);
              
            }
            catch (Exception ex)
            {
                txt_MessageLog.Text += "服務器連接異常\r\n";
            }
        }

        private void But_endlisten_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 接收服務端信息
        /// </summary>
        public void GetInfo(object o)
        {
            Socket clientSocket = o as Socket;
            try
            {
                while (kg)
                {
                    bytes = clientSocket.Receive(recBytes, recBytes.Length, SocketFlags.None);
                    if (bytes <= 0)
                    {
                        txt_MessageLog.Invoke(new invokeInfo(Output), "服務器連接已經關閉");
                        if (clientSocket.Connected)
                            clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Disconnect(false);
                        clientSocket.Close();
                        break;
                    }
                    recStr = Encoding.UTF8.GetString(recBytes, 0, bytes);
                    txt_MessageLog.Invoke(new invokeInfo(Output), recStr);
                }
            }
            catch (Exception ex)
            {
                txt_MessageLog.Invoke(new invokeInfo(Output), "服務器的信息接收異常,原因:" + ex.Message+"\r\n");
            }
        }

        /// <summary>
        /// 關閉Socket
        /// </summary>
        public void Close()
        {
            try
            {
                kg = false;
                if (clientSocket.Connected)
                    clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch { }
        }

    }
}

客戶端界面:

客戶端代碼:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved