之前用UdpClient,发现当开了一个端口用于监听接收,则不能再用来发送(反之亦然)。这样对于简单的收发信息来说无问题,但如果需要nat穿透的程序,则变得困难。用Socket类则不存在该问题,参考下面示例代码:
class Program
{
static void Main(string[] args)
{
SocketTest test = new SocketTest();
test.StartReceive();
Console.WriteLine("请输入对端口号,准备发送:");
string port = Console.ReadLine();
test.SendData(Encoding.UTF8.GetBytes("你好吗?"), IPAddress.Parse("127.0.0.1"), Convert.ToInt32(port));
Console.ReadKey(true);
}
}
public class SocketTest
{
private Socket _socket;
IPEndPoint _local = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5238);
Thread _receiveThread = null;
public void StartReceive()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_receiveThread = new Thread(Receive);
_receiveThread.Start();
}
public void SendData(byte[] data, IPAddress remoteIP, int remotePort)
{
_socket.SendTo(data, new IPEndPoint(remoteIP, remotePort));
}
public void Close()
{
if (_receiveThread != null)
_receiveThread.Abort();
if (_socket != null)
_socket.Close();
}
private void Receive()
{
_socket.Bind(_local);
Console.WriteLine("开始接收。。。");
while (true)
{
byte[] buffer = new byte[1024];
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
int len = _socket.ReceiveFrom(buffer, ref remoteEP);
IPEndPoint ipEndPoint = remoteEP as IPEndPoint;
Console.WriteLine("收到消息:客户机IP--{0},,端口--{1}", ipEndPoint.Address.ToString(), ipEndPoint.Port.ToString());
Console.WriteLine("消息内容:{0}", Encoding.UTF8.GetString(buffer, 0, len));
}
}
}
转载: http://harvey8819.blog.163.com/blog/static/162365181201123121635983/