我目前正在C#
编写代码,它需要通过套接字与VB6
编写的程序进行通信。 <br/>
当VB6
程序没有运行时,我的C#程序抛出一个SocketException。
我所做的是捕获异常,但我注意到它将继续抛出异常,直到VB6
程序再次运行。<br/><br/>
ReceiveFrom(...)方法处于无限循环中,因此当VB6程序再次运行时,它可以接收数据。<br/><br/>
我想知道是否有更好的方法来解决这个问题。
C#代码看起来像这样......
internal class SocketConnection : Connection
{
private Socket socket;
private EndPoint localEndPoint;
private IPEndPoint remoteIPEndPoint;
internal SocketConnection(int localPortNumber, IPAddress remoteIPAddress, int remotePortNumber)
{
IPEndPoint localIPEndPoint = new IPEndPoint(
GetLocalIPAddress(),
localPortNumber);
socket = new Socket(
localIPEndPoint.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
socket.Bind(localIPEndPoint);
localEndPoint = (EndPoint)localIPEndPoint;
Thread receiver = new Thread(() => Receive());
receiver.Start();
remoteIPEndPoint = new IPEndPoint(remoteIPAddress, remotePortNumber);
}
private void Receive()
{
byte[] msg = new Byte[256];
while (true)
{
try
{
socket.ReceiveFrom(msg, ref localEndPoint);
buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
}
catch (SocketException)
{
buffer = string.Empty;
}
}
}
private IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
throw new Exception("Local IP Address Not Found!");
}
protected override void Interrogate(string message)
{
socket.SendTo(Encoding.ASCII.GetBytes(message), remoteIPEndPoint);
}
}
答案 0 :(得分:1)
在调用ReceiveFrom
之前,您应该检查套接字中是否有要读取的内容:
int available = socket.Available;
if (available > 0)
{
socket.ReceiveFrom(msg, 0, Math.Min(msg.Length, available), SocketFlags.None, ref localEndPoint);
buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
}