请看这里http://developer.ccidnet.com/pub/article/c1137_a73028_p1.html
解决方案 »
- 如果datagridview的数据源是datatable,怎么设置列为comboBox
- 如何跳过360等软件的提示修改注册表????仅仅娱乐...
- 窗口关闭问题……
- winform 触发器
- 请问Spring.NET可否免费用于商业项目?有什么限制?
- 如何根据某个程序标题栏文字得到其进程并关闭有这个标题栏文字的所有程序.
- 我想在combobox Items中添加panel 怎么做呢?
- 高分:执行TLBIMP后的msword.dll文件还是不能加入的COM组件!
- 帮帮小弟啊(因为自己没分,所以给不了分)
- 一个项目工程太大,接盘的时候调试不知道断点打在哪
- 高分求救:访问虚拟目录Exception from HRESULT: 0x80005008.
- 板竹请进,
[Visual Basic, C#, C++] The following example establishes a UdpClient connection using the host name www.contoso.com on port 11000. A small string message is sent to two separate remote host machines. The Receive method blocks execution until a message is received. Using the IPEndPoint passed to Receive, the identity of the responding host is revealed.// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient();
try{
udpClient.Connect("www.contoso.com", 11000); // Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length); // Sends a message to a different host using optional hostname and port parameters.
UdpClient udpClientB = new UdpClient();
udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000); //IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString()); udpClient.Close();
udpClientB.Close();
}
catch (Exception e ) {
Console.WriteLine(e.ToString());
}Requirements
Namespace: System.Net.Sockets
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.Windows.Forms;public class UDPNewsClient : Form
{
public static void Main ( string[] args )
{
Application.Run ( new UDPNewsClient () );
} // multicast group IP address
private const string GROUP_IP = "225.0.0.1";
// multicast group port
private const int GROUP_PORT = 8081;
// communication interface
private UDPMulticastClient client = null;
// ticker thread
private Thread tickerThread = null;
// new messages
private TextBox text = null;
// default news displayed at the beginning
private string news = "Please wait...";
public UDPNewsClient ()
{
Console.WriteLine ( "initializing client..." );
// create controls
this.Text = "News Client";
this.Size = new Size ( this.Size.Width, 75 );
Label l = new Label ();
l.Text = "News:";
l.Location = new Point ( 10, 10 );
l.Size = new Size ( 40, l.Size.Height );
this.Controls.Add ( l );
this.text = new TextBox ();
this.text.Font = new Font ( "Courier New", 9 );
this.text.Text = "Please wait...";
this.text.Location = new Point ( 50, 10 );
this.text.Size = new Size ( 225, this.text.Size.Height );
this.text.ReadOnly = true;
this.Controls.Add ( this.text );
// add an event listener for close-event
this.Closed += new System.EventHandler ( OnClosed );
// start communication thread
this.client = new UDPMulticastClient ( GROUP_IP, GROUP_PORT, new Notify ( SetNews ) );
// start ticker thread
this.tickerThread = new Thread ( new ThreadStart ( RunTicker ) );
this.tickerThread.Start ();
Console.WriteLine ( "initialization complete" );
}
// stop client
public void OnClosed ( Object sender, EventArgs e )
{
Console.WriteLine ( "client shut down" );
this.client.Close ();
this.tickerThread.Abort ();
this.tickerThread.Join (); Application.Exit ();
}
// ticker thread
public void RunTicker ()
{
// initialze the textbox with the default text
this.text.Text = " -+-+- " + this.news + " -+-+- " + this.news + " -+-+- ";
while ( true )
{
string data = this.news + " -+-+- ";
// repeat as long as there are characters in the data string
while ( !data.Equals ( "" ) )
{
// wait 500 milliseconds
Thread.Sleep ( 500 ); // remove the first character from the text field and add the
// first character of the data string
this.text.Text = this.text.Text.Substring ( 1 ) + data[0];
// remove the first character from the data string
data = data.Substring ( 1 );
}
}
}
// notification method, used by multicast client
public void SetNews ( string news )
{
this.news = news;
}
}
服务器端
using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.Windows.Forms;public class UDPNewsServer : Form
{
public static void Main ( string[] args )
{
Application.Run ( new UDPNewsServer () );
}
// local port where the UDP server is bound to
private const int LOCAL_PORT = 8080;
// multicast group IP address
private const string GROUP_IP = "225.0.0.1";
// multicast group port
private const int GROUP_PORT = 8081;
// UDP server
private UDPPeer server = null;
// a thread for sending new continuously
private Thread serverThread = null;
// a data field for typing in a new message
private TextBox text = null;
// a button for setting the new message
private Button setButton = null;
// the news message
private string news = "";
public UDPNewsServer ()
{
Console.WriteLine ( "initializing server, local port=" + LOCAL_PORT + ", group IP=" + GROUP_IP + ", group port=" + GROUP_PORT + "..." );
// create controls
this.Text = "News Server";
this.Size = new Size ( this.Size.Width, 100 );
Label l = new Label ();
l.Text = "News:";
l.Location = new Point ( 10, 10 );
l.Size = new Size ( 40, l.Size.Height );
this.Controls.Add ( l );
this.text = new TextBox ();
this.text.Location = new Point ( 50, 10 );
this.text.Size = new Size ( 225, this.text.Size.Height );
this.text.Text = "(enter news)";
this.Controls.Add ( this.text );
this.setButton = new Button ();
this.setButton.Text = "Set";
this.setButton.Location = new Point ( 10, 40 );
this.Controls.Add ( this.setButton );
// add an event listener for click-event
this.setButton.Click += new System.EventHandler ( OnSet );
// add an event listener for close-event
this.Closed += new System.EventHandler ( OnClosed );
// create communication components
this.server = new UDPPeer ( LOCAL_PORT, GROUP_IP, GROUP_PORT ); // start communication thread
this.serverThread = new Thread ( new ThreadStart ( Run ) );
this.serverThread.Start ();
Console.WriteLine ( "initialization complete" );
}
// server shut down
public void OnClosed ( Object sender, EventArgs e )
{
Console.WriteLine ( "server shut down..." );
// stop thread
this.serverThread.Abort ();
// wait until it's stopped
this.serverThread.Join ();
this.server.Close (); Application.Exit ();
}
// button click event handler
public void OnSet ( Object sender, EventArgs e )
{
this.news = this.text.Text;
}
// sending thread
public void Run ()
{
while ( true )
{
if ( !this.news.Equals ( "" ) )
{
Console.WriteLine ( "sending " + this.news );
this.server.Send ( this.news );
}
// wait one second
Thread.Sleep ( 1000 );
}
}
}
using System;
using System.Net;
using System.Net.Sockets;public class UDPHelloWorldServer
{
public static void Main ()
{
Console.WriteLine ( "initializing server" );
UdpClient server = new UdpClient ( 8080 );
// an endpoint is not needed the data will be sent
// to the port where the server is bound to
IPEndPoint dummy = null;
bool loop = true;
while ( loop )
{
Console.WriteLine ( "waiting for request..." );
byte[] datagram = server.Receive ( ref dummy );
// split request string into parts, part1=client IP address or
// DNS name, part2=client port, part3=command
string dg =
new System.Text.ASCIIEncoding ().GetString ( datagram );
string[] cmd = dg.Split ( new Char[] {':'} );
string remoteClientHost = cmd[0];
int remoteClientPort = Int32.Parse ( cmd[1] );
string command = cmd[2];
string result = null;
Console.WriteLine ( "executing remote command:" + command );
switch ( command )
{
case "GET":
result = "Hello World !";
break;
// finish communication
case "EXIT":
result = "BYE";
loop = false;
break;
// invalid command
default:
result = "ERROR";
break;
}
if ( result != null )
{
Console.WriteLine ( "sending result to (" + remoteClientHost + ":" + remoteClientPort + "): " + result );
// convert data string to byte array
Byte[] d = System.Text.Encoding.ASCII.GetBytes ( result.ToCharArray () );
// send result to the client
server.Send ( d, d.Length, remoteClientHost, remoteClientPort );
}
}
Console.WriteLine ( "clearing up server..." );
server.Close ();
Console.Write ( "press return to exit" );
Console.ReadLine ();
}
}客户端using System;public class UDPHelloWorldClient
{
public static void Main ()
{
Console.WriteLine ( "initializing client..." );
UDPRemoteCommandProcessor proc = new UDPRemoteCommandProcessor ( 8081, "127.0.0.1", 8080 );
string result = null;
Console.WriteLine ( "requesting..." );
proc.Execute ( "GET", ref result );
Console.WriteLine ( "result: " + result );
Console.WriteLine ( "closing connection..." );
proc.Execute ( "EXIT", ref result );
proc.Close ();
Console.Write ( "press return to exit" );
Console.ReadLine ();
}
}
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);你的例子我也看了,在SDK上的,我都试过,执行到第二句时,出现错误 10022
"提供了一个错误的参数". 我莫明其妙,不知道怎么回事.
IPEndPoint dummy = null;
bool loop = true;
while ( loop )
{
Console.WriteLine ( "waiting for request..." );
byte[] datagram = server.Receive ( ref dummy );你的那段代码在我的计算机上会出现 "参数不能为空"的异常!
byte[] datagram = server.Receive ( ref dummy );
这一句. 我莫明其妙,我看到网络上有象你这样写的,为何在我的计算机上就不行呢?难道是操作系统的问题?
我用笔记本计算机 DELL C640 P4 1.8G 256MB 3COM920网卡.网络很正常
----不在一个网段内的机器无法使用UDP通讯,UDP十部能够跨网段的,路由器不会转发UDP数据报,所以不能实现这样的功能
是不能转发UDP数据报,而不是TCP数据包;
两者截然不同。QQ和MSN绝对用的都不是UDP,因为这两个工具你首先要登陆到指定服务器,这个动作就已经说明他使用的Socket协议是TCP,而不是UDP.
但是你和朋友聊天的时候,如果互相已经建立连接,数据并不经过服务器中转
如果是TCP,怎么可能做到
去
www.pagediy.com 通信区下载