我有一个控制台应用程序,它等待客户端连接指定的套接字,然后接受客户端,开始提供数据,如果一段时间后客户端应用程序停止,分发器退出自己,但我会让分配器只是改变模式在监听对于客户端,当客户端连接丢失时,分发服务器才开始等待,但同时退出。
static class Program
{
static void Main()
{
Start()
}
}
private void Start()
{
WaitForClientConnection();
//waits till client connect
StartReceive();
}
private void WaitForClientConnection()
{
_tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_tcpSocket.Bind(new IPEndPoint(IPAddress.Parse("172.16.192.40"), 7000));
_tcpSocket.Listen(100);
_tcpClientAcceptSocket = _tcpSocket.Accept();
}
public void StartReceive()
{
try
{
Console.WriteLine("Starting to receive data...");
while (_tcpClient.Connected)
{
//sendind data to client
}
if (!_tcpClient.Connected)
{
// if client socket listener is stops somehow, I also close _tcpClient connection after that start to keep waiting for clients
Console.WriteLine("Closing the connection...");
_tcpClient.Close();
//here start(), and WaitForClientConnection() are begin again(I realized and sure) however in WaitForClientConnection() function exits itself from application not wait for client
Start();
}
}
}
可能是什么问题?
谢谢
答案 0 :(得分:1)
第二次调用WaitForClientConnection()时,尝试将新的侦听套接字绑定到172.16.192.40:7000。从第一次调用WaitForClientConnection()开始,你已经有一个绑定到该地址的套接字。
尝试这样的事情:
private void CreateListener()
{
_tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_tcpSocket.Bind(new IPEndPoint(IPAddress.Parse("172.16.192.40"), 7000));
_tcpSocket.Listen(100);
}
private void Start()
{
if (_tcpSocket == null)
{
CreateListener();
}
WaitForClientConnection();
//waits till client connect
StartReceive();
}
private void WaitForClientConnection()
{
_tcpClientAcceptSocket = _tcpSocket.Accept();
}
真的可以完全摆脱WaitForClientConnection,因为它现在只是一行代码。但那不是我写这个的方式;我只是想接近原始代码。
关键是你创建了一次监听套接字。当你接受对话时它不会消失。
我不知道这是否是唯一的问题。您应该捕获并报告异常,因此我们确切知道什么是终止该过程。