public FeiQIM(int Port) { msgdt.Columns.Add(new DataColumn("ip", System.Type.GetType("System.String"))); msgdt.Columns.Add(new DataColumn("msg", System.Type.GetType("System.String"))); msgdt.Columns.Add(new DataColumn("msgid", System.Type.GetType("System.String"))); if (!FunctionUtils.checkPort(Port.ToString())) { throw new Exception("端口被占用"); } else { UdpClient = new System.Net.Sockets.UdpClient(Port); UdpClient.JoinMulticastGroup(GroupIP); //BroadcastOnLine(); } }
/// <summary> /// send message to others /// </summary> /// <param name="destinationIP">the destination ip ,e.g.,192.168.1.1</param> /// <param name="msg">message you want to send</param> public static void SendMessage(string destinationIP, string msg) { System.Net.Sockets.TcpClient tcpClient = null; System.Net.Sockets.NetworkStream netStream = null; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg); var destIP = System.Net.IPAddress.Parse(destinationIP); var myIP = Communication.GetLocalIP(); //var myIP = "192.10.110.54"; var epDest = new System.Net.IPEndPoint(destIP, 1124); Random ro = new Random(); int up = 1150; int down = 1123; var sendport = 1123; while (!FunctionUtils.checkPort(sendport.ToString()))//检查端口占用 { sendport = ro.Next(down, up); } var dpLocal = new System.Net.IPEndPoint(myIP, sendport); tcpClient = new System.Net.Sockets.TcpClient(dpLocal); tcpClient.Connect(epDest); netStream = tcpClient.GetStream(); if (netStream.CanWrite) { netStream.Write(buffer, 0, buffer.Length); } tcpClient.GetStream().Close(); tcpClient.Client.Close(); tcpClient.Close(); // tcpClient.GetStream().Close(); // tcpClient.Client.Disconnect(false); //tcpClient.Close(); }