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 { }
        }

    }
}

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn