C#异步套接字-代码分析
在我第二次向服务器发出请求后,我的客户端部分将关闭,但没有出现错误,它只是消失了:C#异步套接字-代码分析,c#,console-application,asyncsocket,C#,Console Application,Asyncsocket,在我第二次向服务器发出请求后,我的客户端部分将关闭,但没有出现错误,它只是消失了: class Client { static void Main(string[] args) { try { Console.Title = "Client"; AsyncClient client = new AsyncClient(60101); client.Connect();
class Client
{
static void Main(string[] args)
{
try
{
Console.Title = "Client";
AsyncClient client = new AsyncClient(60101);
client.Connect();
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
}
public class AsyncClient
{
private IPAddress ipAddress;
private int port;
/// <summary>
/// Connects to the local IPAddress.
/// </summary>
/// <param name="port"></param>
public AsyncClient(int port)
{
this.port = port;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
this.ipAddress = null;
for (int i = 0; i < ipHostInfo.AddressList.Length; i++)
{
if (ipHostInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
this.ipAddress = ipHostInfo.AddressList[i];
break;
}
}
if (this.ipAddress == null)
throw new Exception("No IPv4 address has been found");
}
public AsyncClient(string ip, int port)
{
this.port = port;
IPAddress.TryParse(ip, out ipAddress);
}
public async void Connect()
{
int attempts = 0;
TcpClient client = new TcpClient();
while (!client.Connected)
{
try
{
attempts++;
client.Connect(this.ipAddress, this.port);
Console.Clear();
Console.WriteLine("Connected");
await Process(client);
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Connection Attempts: {0}", attempts);
}
}
}
public async Task Process(TcpClient tcpClient)
{
try
{
NetworkStream stream = tcpClient.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
writer.AutoFlush = true;
while (true)
{
Console.WriteLine("Enter a Request: ");
await writer.WriteLineAsync(Console.ReadLine());
string response = await reader.ReadLineAsync();
if (response != null)
Console.WriteLine(response);
else
break;
}
}
catch (Exception)
{
//
}
finally
{
if (!tcpClient.Connected)
{
for (int i = 5; i >= 1; i--)
{
Console.WriteLine($"Connection lost, trying to reconnect in {i}");
Thread.Sleep(1000);
}
Connect();
}
}
}
}
类客户端
{
静态void Main(字符串[]参数)
{
尝试
{
Console.Title=“客户端”;
AsyncClient=新的AsyncClient(60101);
client.Connect();
Console.Read();
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
Console.Read();
}
}
}
公共类异步客户端
{
私人IP地址;
专用int端口;
///
///连接到本地IP地址。
///
///
公共异步客户端(int端口)
{
this.port=端口;
IPHostEntry ipHostInfo=Dns.GetHostEntry(Dns.GetHostName());
this.ipAddress=null;
for(int i=0;i=1;i--)
{
WriteLine($“连接丢失,试图在{i}中重新连接”);
睡眠(1000);
}
Connect();
}
}
}
}
下面是服务器端代码,仅供学习之用。我正在尝试学习如何使用套接字,在尝试了许多不同的方法(如“开始”方法等)之后,我觉得我终于找到了正确的方法,因为其他方法存在并发访问、关闭连接等问题,但这次我相信我做对了。
是我错了还是这次我的代码真的很好
class Server
{
static void Main(string[] args)
{
try
{
Console.Title = "Server";
AsyncServer server = new AsyncServer(60101);
server.Run();
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
}
public class AsyncServer
{
private IPAddress ipAddress;
private int port;
public AsyncServer(int port)
{
this.port = port;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
this.ipAddress = null;
for (int i = 0; i < ipHostInfo.AddressList.Length; i++)
{
if (ipHostInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
this.ipAddress = ipHostInfo.AddressList[i];
break;
}
}
if (this.ipAddress == null)
throw new Exception("No IPv4 address for server");
}
public async void Run()
{
TcpListener listener = new TcpListener(this.ipAddress, this.port);
listener.Start();
Console.WriteLine($"Server is now online on Port: {this.port}");
Console.WriteLine("Hit <Enter> to stop the service");
while (true)
{
try
{
TcpClient tcpClient = await listener.AcceptTcpClientAsync();
Process(tcpClient);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private async void Process(TcpClient tcpClient)
{
string clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
Console.WriteLine($"Received connection request from {clientEndPoint}");
try
{
NetworkStream networkStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(networkStream);
StreamWriter writer = new StreamWriter(networkStream);
writer.AutoFlush = true;
while (true)
{
string request = await reader.ReadLineAsync();
if (request != null)
Handle(request, writer);
else
break;
}
}
catch (Exception)
{
//
}
finally
{
if (tcpClient.Connected)
tcpClient.Close();
Console.WriteLine($"{clientEndPoint} has closed the connection, aborting operation");
}
}
private string Response(string request)
{
Thread.Sleep(10000);
if (request.ToLower() == "get time")
return DateTime.Now.ToLongTimeString();
else
return $"\"{request}\" is a invalid request";
}
private async void Handle(string request, StreamWriter writer)
{
try
{
Console.WriteLine($"Received request: {request}");
string response = Response(request);
Console.WriteLine($"Computed response is: {response}");
await writer.WriteLineAsync(response);
}
catch (Exception)
{
//
}
}
}
类服务器
{
静态void Main(字符串[]参数)
{
尝试
{
Console.Title=“服务器”;
AsyncServer=新的AsyncServer(60101);
server.Run();
Console.Read();
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
Console.Read();
}
}
}
公共类异步服务器
{
私人IP地址;
专用int端口;
公共异步服务器(int端口)
{
this.port=端口;
IPHostEntry ipHostInfo=Dns.GetHostEntry(Dns.GetHostName());
this.ipAddress=null;
for(int i=0;ipublic async Task ConnectAsync()
client.ConnectAsync().Wait();
static async Task Main(string[] args)
{
...
await client.ConnectAsync();
...
}