【发布时间】:2023-03-09 19:58:01
【问题描述】:
我正在尝试制作一个 Steam Like Friends Client ...
我可以连接到服务器,但是如果服务器崩溃,我该如何重新连接 .. . 并继续重新连接,直到服务器重新启动...
public void ConnectToUserServer()
{
lb_ConnectStatus.Text = "Connecting ... ";
lb_ClientInfo.Text = "";
byte[] sendBytes = new byte[10025];
UserName = tb_UserName.Text;
//Create an instance of TcpClient.
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(serverName), UsersPort);
tcpClient.Connect(ipend);
lb_ConnectStatus.Text = "Connected ... ";
string HostName = Dns.GetHostName().ToString();
IPAddress[] IpInHostAddress = Dns.GetHostAddresses(HostName);
string IPV4Address = IpInHostAddress[2].ToString(); //Default IPV4Address.
// LocalEndPoint will return the ip address and port to which the tcp connection is accepted
var clientIpLAN = tcpClient.Client.LocalEndPoint;
lb_ClientInfo.Text = HostName + " " + IPV4Address;
networkStream = tcpClient.GetStream();
send = UserName + " : " + IPV4Address;
sendBytes = Encoding.ASCII.GetBytes(send);
networkStream.Write(sendBytes, 0, sendBytes.Length);
t = new Thread(DoWork);
t.IsBackground = true;
t.Start();
}
从服务器接收用户列表
public void DoWork()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = networkStream.Read(bytes, 0, bytes.Length);
}
tcpClient.Close();
ConnectToUserServer();
}
先谢过
【问题讨论】:
-
重连和第一次连不一样吗?
-
当服务器关闭时,客户端崩溃,正在尝试重新连接,直到服务器再次启动...
-
哦,你的意思是你想继续尝试重新连接?我想:尝试重新连接 -> 失败 -> 暂停 -> 重复直到连接成功。