C#多线程数组模拟socket
更新时间:2017年06月30日 09:59:22 作者:北冥冰皇
这篇文章主要为大家详细介绍了C#多线程数组模拟socket的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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# winfroms使用socket客户端服务端的示例代码
这篇文章主要为大家详细介绍了C# winfroms使用socket客户端服务端的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下2024-02-02
最新评论