读书人

用udp写个服务器如何获取客户端的ipep

发布时间: 2013-04-21 21:18:07 作者: rapoo

用udp写个服务器怎么获取客户端的ipep?
看了msdn中的代码,客户端的ip是人为指定的,而不能处理多个客户端的接入
是不是服务器客户端的程序服务器端只能用tcp连接,而不能用udp的无连接协议?
udp作为无连接的只能用于点对点的通信?



public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);

Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}

public static void ReceiveMessages()
{
// Receive a message and write it to the console.
IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
UdpClient u = new UdpClient(e);

UdpState s = new UdpState();
s.e = e;
s.u = u;

Console.WriteLine("listening for messages");
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

// Do some work while we wait for a message. For this example,
// we'll just sleep
while (!messageReceived)
{
Thread.Sleep(100);
}
}

[解决办法]
internal void OnDataReceived(IAsyncResult ar)
{

try
{
Socket udpSocket = ar.AsyncState as Socket;


int bytesRecved = udpSocket.EndReceiveFrom(ar, ref remoteEP);
string ip=remoteEP.split(':')[0]; //对方ip
string port=remoteEP.split(':')[1];//对方端口
...

读书人网 >C#

热点推荐