多线程下SOCKET编程

SOCKET编程往往离不开多线程,说到多线程,总的说来还是一个比较复杂的东西,尤其是业务逻辑变得复杂的时候,有时候或者说经常,会弄得人头晕脑胀。但是C#,相对好一点,因为微软封装了,帮我们做很多工作,但是在实际的编码过程中,往往会出现各种各样的错误或者BUG。

这里先写一个简单的多线程函数,这样有个初步的理解,也算是入门了,相信大家不用多论述就能明白。

public static void Start()
        {
            Thread t1 = new Thread(ExceMethod);
            t1.IsBackground = true;
            t1.Start();

            Console.WriteLine(DateTime.Now);
        }

        private static void ExceMethod()
        {
           while(true){
                Console.WriteLine(DateTime.Now);
                
               //do anything

               Thread.Sleep(1000);
            }
        }

   如果两个方法都去掉static 也是可以的。这样就实现了多线程,简单吧。当如如果仅仅是这个代码,恐怕也没什么意义哦,这个只是表示我们已经实现了多线程。多线程主要用在有阻塞的场合下。

  在这里我们和SOCKET结合起来使用,SOCKET多线程服务器端代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ConsoleSocketServer
{
    class Program
    {
        private static TcpListener tcpServer = null;
        
        private static byte[] bytes = new byte[256];

        static void Main(string[] args)
        {
            IPAddress iPAddress = IPAddress.Any;
            tcpServer = new TcpListener(iPAddress, 999);
            //999是端口号,可以随便改 0-1024,主要不要和什么80,8080之类的常用端口号相冲突哦。

              tcpServer.Start();
            Console.WriteLine("监听已启动......");

            Thread t1 = new Thread(ExceMethod);
            t1.IsBackground = true;
            t1.Start();

            Console.ReadKey();
        }

        private static void ExceMethod()
        {
            byte[] msg = Encoding.UTF8.GetBytes("服务端数据");

           while(true){
               TcpClient client = tcpServer.AcceptTcpClient();
               while (true)
               {
                   try
                   {
                       int i = client.Client.Receive(bytes);

                       Console.WriteLine(DateTime.Now.ToString("G") + "接受:" + Encoding.UTF8.GetString(bytes));

                       client.Client.Send(msg);
                   }catch{
                       break;
                   }
               }
               client.Close();

               Thread.Sleep(1000);//10000单位是毫秒,系统在运行过程中,稍微有点停顿,个人感觉会更好一点。
            }
        }
    }
}

SOCKET多线程客户端代码

using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;


namespace ConsoleSocketClient
{
    class Program
    {
        private static TcpClient client = new TcpClient();

        static void Main(string[] args)
        {
            client.Connect("127.0.0.1", 999);
            Console.WriteLine("连接成功......");

            Thread t1 = new Thread(ExceMethod);
            t1.IsBackground = true;
            t1.Start();

            Console.ReadKey();
        }
        
        private static void ExceMethod()
        {
            while (true) { 
            byte[] data = Encoding.UTF8.GetBytes("客户端数据");
            Socket socket = client.Client;
            socket.Send(data, data.Length, SocketFlags.None);
            //Console.WriteLine("发送成功" + Encoding.UTF8.GetString(data));

            socket.Receive(data, SocketFlags.None);
            Console.WriteLine("接受数据" +  Encoding.UTF8.GetString(data));
            Thread.Sleep(1000);

            }
        }

        }
    }


到这里路就走通了。但是这个也只能算是演示代码,在实战中,不仅有业务逻辑的,还应该有更多的抓错和判断。在这里只是想帮助大家更好的理解SOCKET编程。而且代码的具体写法与业务场景是有关系的。这里顶多也只能算是点到为止。

当然,多线程模式的SOCKET编程一般与通讯程序有关系,后面如果有时间,再写写在自动化行业的modbus协议数据的读取。因为读modbus数据,就是以SOKET,多线程为基础来实现的。

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值