• 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 += "监听已经打开,请等待
    ";
    
                    Thread conn = new Thread(new ParameterizedThreadStart(GetALLClientConn));
                    conn.IsBackground = true;
                    conn.Start(serverSocke);
                }
                catch (Exception ex)
                {
                    txt_MessageLog.Text += "服务异常
    ";
                }
            }
    
            /// <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 += "服务器连接关闭
    ";
                }
            }
    
            /// <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 + "
    ";
            }
    
            //发送信息
            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 + "
    ";
                    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 += "服务端发送信息异常
    ";
                }
            }
    
            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 + "
    ";
            }
    
            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 + "
    ";
                    byte[] sendBytes = Encoding.UTF8.GetBytes(clientSocket.RemoteEndPoint + ":" + sendStr);
                    int i= clientSocket.Send(sendBytes);
                }
                catch (Exception ex)
                {
                    txt_MessageLog.Text += "信息发送异常
    ";
                }
            }
    
            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 += "连接成功
    ";
                    groupBox1.Text += txt_IP.Text;
                    Thread t = new Thread(new ParameterizedThreadStart(GetInfo));
                    t.IsBackground = true;
                    t.Start(clientSocket);
                  
                }
                catch (Exception ex)
                {
                    txt_MessageLog.Text += "服务器连接异常
    ";
                }
            }
    
            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+"
    ");
                }
            }
    
            /// <summary>
            /// 关闭Socket
            /// </summary>
            public void Close()
            {
                try
                {
                    kg = false;
                    if (clientSocket.Connected)
                        clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
                catch { }
            }
    
        }
    }



    客户端界面:

    客户端代码:

  • 相关阅读:
    mysql 之 double( totalsize, decimal)
    java8 实战--- Map merge用法
    java8 stream接口 终端操作 min,max,findFirst,findAny
    tinyint(1)详解
    表单插件——form
    表单验证插件——validate
    使用ajaxStart()和ajaxStop()方法
    使用ajaxSetup()方法设置全局Ajax默认选项
    使用ajax()方法加载服务器数据
    使用serialize()方法序列化表单元素值
  • 原文地址:https://www.cnblogs.com/bieyang/p/socket_communication.html
Copyright © 2020-2023  润新知