概述
本文实例为大家分享了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}! rn 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}! rn Socket Client {1}", pkt.BytesToStr(datapkt), strAddress)); System.Threading.Thread.Sleep(1000 * timerheart); } } catch (Exception ex) { WriteLine(string.Format("Exception:{0} rn Socket Client {1}", ex.ToString(), strAddress)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。
最后
以上就是闪闪西装为你收集整理的C#多线程数组模拟socket的全部内容,希望文章能够帮你解决C#多线程数组模拟socket所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复