这个问题在TX 面试的时候问过我。 不过当时demo并没有注意这个问题, 还好面试官换问题了。。
一、正常关闭
如果客户端是主动申请close , 会发送一串byte数 为0的数据到服务器,服务器就会收到count个数为0,则表示正常关闭。此时服务器正常操作close(这里有个问题是,即便客户端自己正常发送空数据进来,服务器也不会收到0数据,所以当服务器收到0的时候就代表客户端请求正常关闭)。
二、异常关闭
如果客户端强制点了X ,则代表未经过(退出游戏)正常关闭操作,当服务器捕获异常(远程主机强制关闭),则停止这个socket连接
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace TcpServer
{
class Program
{
static byte[] dataBuffer = new byte[1024];
static void Main(string[] args)
{
StartServerAsync();
Console.ReadKey();
}
static void StartServerAsync()
{
Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress iPAddress = IPAddress.Parse("192.168.200.1");
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 88);
socketServer.Bind(iPEndPoint);
socketServer.Listen(10);
//Socket clientSocket = socketServer.Accept(); 下面支持多个客户端,改为异步, 之前c++服务器用的epoll这里似乎不需要关注
socketServer.BeginAccept(AcceptCallBack, socketServer);
}
static void AcceptCallBack(IAsyncResult ar)
{
Socket socketServer = ar.AsyncState as Socket;
Socket socketClient = socketServer.EndAccept(ar);
string msg = "Hello";
socketClient.Send(System.Text.Encoding.UTF8.GetBytes(msg));
socketClient.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, socketClient);
socketServer.BeginAccept(AcceptCallBack, socketServer);
}
static void ReceiveCallBack(IAsyncResult ar)
{
// ar.AsyncState 可以获得之前传递的object
Socket socketClient=null ;
try
{
socketClient = ar.AsyncState as Socket;
int count = socketClient.EndReceive(ar);
if (count == 0)
{
//即便是空数据也不会是0,客户端不会发送空数据, 只有在结束时才有0的可能性
socketClient.Close();
return;
}
string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0, count);
Console.WriteLine(msgReceive);
socketClient.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, socketClient);
}
catch (Exception e)
{
Console.WriteLine(e);
if (socketClient != null)
{
socketClient.Close();
}
}
}
void StartServerSync()
{
Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress iPAddress = IPAddress.Parse("192.168.200.1");
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 88);
socketServer.Bind(iPEndPoint);
socketServer.Listen(10);
Socket clientSocket = socketServer.Accept();
string msg = "Hello";
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(msg));
byte[] databuffer = new byte[1024];
int count = clientSocket.Receive(databuffer);
string megReceive = System.Text.Encoding.UTF8.GetString(databuffer, 0, count);
Console.Write(databuffer);
clientSocket.Close();
socketServer.Close();
}
}
}
————————————————
版权声明:本文为CSDN博主「YYyyCCCcccBb」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_33951440/article/details/79863661