大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要介绍C#中多线程数组如何模拟socket,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
“只有客户发展了,才有我们的生存与发展!”这是创新互联公司的服务宗旨!把网站当作互联网产品,产品思维更注重全局思维、需求分析和迭代思维,在网站建设中就是为了建设一个不仅审美在线,而且实用性极高的网站。创新互联对成都网站设计、成都网站建设、网站制作、网站开发、网页设计、网站优化、网络推广、探索永无止境。
具体内容如下
代码如下
//实例化线程组 Thread[] clientThreads = new Thread[numThread]; for (int i = 0; i < numThread; i++) { clientThreads[i] = new Thread(new ParameterizedThreadStart(SocketClient)); clientThreads[i].Start(i); }
多线程组模拟socket发送
static void SocketClient(object s) { //本机地址字符串 string strAddress = (13010001000 + Convert.ToInt32(s)).ToString() + "0"; IPHostEntry ipHost = DNS.Resolve(ipServer); IPAddress ipAddress = ipHost.AddressList[0]; IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, portServer); //实例化套接字 Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socketClient.Connect(ipEndPoint); WriteLine(string.Format("Successfully connected to {0}! Socket Client {1}", socketClient.RemoteEndPoint, strAddress)); byte[] byteAddr = new byte[6]; byteAddr[0] = Convert.ToByte(strAddress.Substring(0, 2), 0x10); byteAddr[1] = Convert.ToByte(strAddress.Substring(2, 2), 0x10); byteAddr[2] = Convert.ToByte(strAddress.Substring(4, 2), 0x10); byteAddr[3] = Convert.ToByte(strAddress.Substring(6, 2), 0x10); byteAddr[4] = Convert.ToByte(strAddress.Substring(8, 2), 0x10); byteAddr[5] = Convert.ToByte(strAddress.Substring(10, 2), 0x10); Packet pkt = new Packet(); byte[] heartpkt = pkt.SendHeartPkt(byteAddr, addrTarget); int times = timerdata / timerheart; Random rd = new Random(); while (true) { for (int i = 0; i < times - 1; i++) { socketClient.Send(heartpkt); WriteLine(string.Format("Send: {0}! \r\n Socket Client {1}", pkt.BytesToStr(heartpkt), strAddress)); System.Threading.Thread.Sleep(1000 * timerheart); } UInt16 i1 = (UInt16)rd.Next(100); UInt16 i2 = (UInt16)rd.Next(100); UInt16 i3 = (UInt16)rd.Next(100); UInt16 i4 = (UInt16)rd.Next(100); UInt16 i5 = (UInt16)rd.Next(100); byte[] byte1 = BitConverter.GetBytes(i1); byte[] byte2 = BitConverter.GetBytes(i2); byte[] byte3 = BitConverter.GetBytes(i3); byte[] byte4 = BitConverter.GetBytes(i4); byte[] byte5 = BitConverter.GetBytes(i5); byte[] databyte = new byte[10]; databyte[0] = byte1[1]; databyte[1] = byte1[0]; databyte[2] = byte2[1]; databyte[3] = byte2[0]; databyte[4] = byte3[1]; databyte[5] = byte3[0]; databyte[6] = byte4[1]; databyte[7] = byte4[0]; databyte[8] = byte5[1]; databyte[9] = byte5[0]; byte[] datapkt = pkt.SendDataPkt(byteAddr, addrTarget, databyte); socketClient.Send(datapkt); WriteLine(string.Format("Send: {0}! \r\n Socket Client {1}", pkt.BytesToStr(datapkt), strAddress)); System.Threading.Thread.Sleep(1000 * timerheart); } } catch (Exception ex) { WriteLine(string.Format("Exception:{0} \r\n Socket Client {1}", ex.ToString(), strAddress)); } }
以上是“C#中多线程数组如何模拟socket”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!