日期:2014-05-18 浏览次数:22058 次
public void sendUdp()
{
string str = "I'm running";
UdpClient udp = new UdpClient(2525);
try
{
while (true)
{
IPAddress ipAdd = IPAddress.Parse("255.255.255.255");
IPEndPoint end = new IPEndPoint(ipAdd, 2020);
try
{
byte[] sendByte = Encoding.Unicode.GetBytes(str);
udp.Send(sendByte, sendByte.Length, end);
}
catch (Exception)
{
throw;
}
Thread.Sleep(3000);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw;
}
}
public void sendTcp(string ipAddress,string str)
{
IPAddress ip = IPAddress.Parse(ipAddress);
IPEndPoint ipep = new IPEndPoint(ip, 2025);
//创建套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接到发送端
try
{
client.Connect(ipep);
}
catch (Exception)
{
MessageBox.Show("指定的从服务器已意外关闭, 链接不上");
}
if (client.Connected)
{
try
{
this.SendVarData(client, Encoding.Unicode.GetBytes(str));
}
catch (Exception)
{
MessageBox.Show("传输文件失败!");
throw;
}
public static int SendVarData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);
while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}