Socket通信的简单运用——服务端的简要dome

这是我第一次接触socket通信,并开启了第一次socket编程,下面就带大家一起检验一下我的学习成果。因为必要的业务需求,我开发了一个通信工具与厂家的软件通信,进行数据的发送与接收,关联业务数据。

这个通讯工具软件类似于网络调试助手,就是自动获取本机IP,自行输入端口号,当然与之通讯的软件也需要输入相同的IP和端口号,然后点击连接之后,通讯就建立了,下一步就是发送条码数据,客户端软件接收到条码数据后,进行相关业务操作后,把业务数据及时反馈给服务端软件(我开发的这个通讯工具软件),最后工具软件再将接收到的数据传入数据库。下面是源代码:

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.Threading.Tasks;
using System.Windows.Forms;

namespace ScrewCommunicationTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textIP.Text = Common.IPAddress;
            labMsg.Text = "";
        }
        /// <summary>
        /// 负责通信的Socket
        /// </summary>
        Socket socketSend;

        /// <summary>
        /// 负责监听Socket
        /// </summary>
        Socket socket;

        /// <summary>
        /// 存放连接的Socket
        /// </summary>
        Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //创建监听的Socket,
            //SocketType.Stream 流式对应tcp协议
            //Dgram,数据报对应UDP协议
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建IP地址和端口号
            IPAddress ip = IPAddress.Parse(textIP.Text.Trim());
            int port = Convert.ToInt32(textPort.Text.Trim());
            IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
            //让负责监听的Socket绑定ip和端口号
            socket.Bind(iPEndPoint);
            //ShowLog("监听成功!" + ip + "\t" + port);//打印日志
            //设置监听队列
            socket.Listen(10);//一段时间内可以连接到的服务器的最大数量
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socket);
        }

        /// <summary>
        /// 使用线程来接收数据
        /// </summary>
        /// <param name="o"></param>

        private void Listen(object o)
        {
            Socket socket = o as Socket;
            while (true)
            {
                //负责监听的Socket是用来接收客户端连接
                //创建负责通信的Socket
                socketSend = socket.Accept();
                dictionary.Add(textIP.Text.Trim(), socketSend);
                //ShowLog(socketSend.RemoteEndPoint.ToString() + "已连接");
                //开启新线程,接收客户端发来的信息
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start(socketSend);
            }
        }

        //服务器接收客户端传来的消息
        private void receive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    //客户端连接成功后,服务器接收客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
                    //接收到的有效字节数
                    int length = socketSend.Receive(buffer);
                    if (length == 0)
                    {
                        //ShowLog(socketSend.RemoteEndPoint.ToString() + "下线了。");
                        dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Close();
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, length);
                    string msg = str.Replace("\0","");
                    labMsg.Text = msg;
                    //ShowLog(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        / <summary>
        / 日志打印
        / </summary>
        / <param name="str"></param>
        //private void ShowLog(string str)
        //{
        //    textLog.AppendText(str + "\r\n");
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消对跨线程调用而产生的错误
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 关闭前关闭Socket
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Disconnect(false);
                socket.Close();
            }
            catch
            {
                socket.Close();
            }
        }

        private void textScan_KeyUp(object sender, KeyEventArgs e)
        {
            string txt = textScan.Text+','+"100"+','+"1000"+','+"1";
            byte[] buffer = Encoding.UTF8.GetBytes(txt);
            List<byte> list = new List<byte>();
            list.Add(0); // 0为发消息
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            string ip = textIP.Text.Trim();
            Socket socketsend = dictionary[ip];
            socketsend.Send(newBuffer);
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ScrewCommunicationTool
{
    public class Common
    {
        static Hashtable temporaryCustCodeLengthTable = new Hashtable();


        public static void ShowMessageBoxInformation(string msg, string title)
        {
            MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public static void ShowMessageBoxError(string msg, string title)
        {
            MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void PlaySoundSuccess()
        {
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
            sp.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "Media\\Success.wav";
            //sp.SoundLocation = System.Environment.CurrentDirectory + "\\Success.wav";
            sp.Play();
        }

        public static void PlaySoundFail()
        {
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
            sp.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "Media\\Error.wav";
            //sp.SoundLocation = System.Environment.CurrentDirectory + "\\Error.wav";
            sp.Play();
        }

        public static void PlaySoundError()
        {
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
            sp.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "Media\\Error.wav";
            //sp.SoundLocation = System.Environment.CurrentDirectory + "\\Error.wav";
            sp.Play();
        }



        public static bool IsNumeric(string s)
        {
            bool ret = true;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] > '9' || s[i] < '0')
                {
                    ret = false;
                    break;
                }
            }
            return ret;
        }

        public static bool IsUpperAlphaNumeric(string s)
        {
            bool ret = true;
            for (int i = 0; i < s.Length; i++)
            {
                if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z')))
                {
                    ret = false;
                    break;
                }
            }
            return ret;
        }

        public static bool IsUpperAlpha(string s)
        {
            bool ret = true;
            for (int i = 0; i < s.Length; i++)
            {
                if (!(s[i] >= 'A' && s[i] <= 'Z'))
                {
                    ret = false;
                    break;
                }
            }
            return ret;
        }

        ///<summary> 转半角的函数(DBC case) </summary>
        ///<param name="input">任意字符串</param>
        ///<returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288,半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        ///</remarks>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();

            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }

                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        public static string GetApplicationVersion()
        {
            string version = "";
            try
            {
                version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            catch { }
            return version;
        }

        public static string IPAddress
        {
            get
            {
                string address = null;
                System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
                if (addresses != null)
                {
                    foreach (System.Net.IPAddress add in addresses)
                    {
                        if (add.ToString().StartsWith("172.") || add.ToString().StartsWith("1."))
                            address = add.ToString();
                    }
                }
                return address;
            }
        }

    }
}

如果想对socket有更多的了解,可以看一下这两个链接:

什么是SOCKET通信,看完马上明白_weixin_52717390的博客-CSDN博客_socket通信

C# winform Socket编程,功能齐全_猪猪派对的博客-CSDN博客_winform socket

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值