0
我正在尝试创建一个程序,以便从网络上的另一台计算机发送和接收字符串。只有通过该程序连接在一起的唯一一对计算机。除了第一次连接之外,大部分工作都已完成并完美工作。只有两台计算机同时打开程序时才能建立第一个连接。由于另一台计算机上的服务器不会运行,因此连接将被拒绝。下面是代码:通过网络等待连接
public MultiplayerState2(Game1 game)
{
this.game = game;
localIp = GetLocalIP();
server = new TcpListener(IPAddress.Parse(localIp), localPort);
server.Start();
networkingThread = new Thread(getData);
networkingThread.Start();
clientThread = new Thread(connectClient);
clientThread.Name = "Connect Client";
clientThread.Start();
}
void connectClient()
{
while (client == null)
{
try
{
client = new TcpClient(remoteIp, remotePort);
Console.WriteLine("Connected");
clientThread.Abort();
}
catch
{
Console.WriteLine("Waiting for partner");
}
}
}
这里,connectClient
应该等待来自计算机的连接。但是我得到的唯一结果是waiting for partner
。这是等待连接的正确方法吗?如果是的话,为什么它不起作用?
抛出什么异常? – FodderZone
@FodderZone这是一个SocketException,这是由客户端尝试连接时未调用TcpListener.Start引起的。 – user26830
请抓住SocketException并查找/传递ErrorCode。 http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx – FodderZone