您好,登錄后才能下訂單哦!
這篇文章主要介紹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”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。