代码如下
//实例化线程组 Thread[] clientThreads = new Thread[numThread]; ; i < numThread; i++) { clientThreads[i] = new Thread(new ParameterizedThreadStart(SocketClient)); clientThreads[i].Start(i); }
多线程组模拟socket发送
static void SocketClient(object s) { //本机地址字符串 + Convert.ToInt32(s)).ToString() + "; IPHostEntry ipHost = Dns.Resolve(ipServer); IPAddress ipAddress = ipHost.AddressList[]; 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)); ]; byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); byteAddr[] = Convert.ToByte(strAddress.Substring(, ), 0x10); Packet pkt = new Packet(); byte[] heartpkt = pkt.SendHeartPkt(byteAddr, addrTarget); int times = timerdata / timerheart; Random rd = new Random(); while (true) { ; i < times - ; i++) { socketClient.Send(heartpkt); WriteLine(string.Format("Send: {0}! \r\n Socket Client {1}", pkt.BytesToStr(heartpkt), strAddress)); System.Threading.Thread.Sleep( * timerheart); } UInt16 i1 = (UInt16)rd.Next(); UInt16 i2 = (UInt16)rd.Next(); UInt16 i3 = (UInt16)rd.Next(); UInt16 i4 = (UInt16)rd.Next(); UInt16 i5 = (UInt16)rd.Next(); 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); ]; databyte[] = byte1[]; databyte[] = byte1[]; databyte[] = byte2[]; databyte[] = byte2[]; databyte[] = byte3[]; databyte[] = byte3[]; databyte[] = byte4[]; databyte[] = byte4[]; databyte[] = byte5[]; databyte[] = byte5[]; 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( * timerheart); } } catch (Exception ex) { WriteLine(string.Format("Exception:{0} \r\n Socket Client {1}", ex.ToString(), strAddress)); } }