Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

异步方法TCP服务端实现示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Program
{
static void Main(string[] args)
{
SeverSocket severSocket = new SeverSocket();
severSocket.Start("127.0.0.1",8080,10);
Console.WriteLine("服务器开启成功");

while (true)
{
String input = Console.ReadLine();
if (input.Substring(0, 2) == "B:")
{
severSocket.Broadcast(input.Substring(2));
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class ClientSocket
{
public Socket socket;
public int clientId;
private static int CLIENT_BEGIN_ID = 1;

private byte[] cacheBytes = new byte[1024];
private int caheNum = 0;
public ClientSocket(Socket socket)
{
this.clientId = CLIENT_BEGIN_ID++;
this.socket = socket;

//开始收消息
this.socket.BeginReceive(cacheBytes,caheNum,cacheBytes.Length,SocketFlags.None,ReceiveCallback,this.socket);
}
private void ReceiveCallback(IAsyncResult result)
{
try
{
caheNum = this.socket.EndReceive(result);
//通过字符串解析
Console.WriteLine(Encoding.UTF8.GetString(cacheBytes, 0, caheNum));
//因为这里是只解析字符串 所以解析完就 再从头开始
caheNum = 0;
//如果是链接状态 就继续收消息
if(socket.Connected)
this.socket.BeginReceive(cacheBytes,caheNum,cacheBytes.Length,SocketFlags.None,ReceiveCallback,this.socket);
else
{
Console.WriteLine("没有链接,不用在接消息");
}
}
catch (SocketException e)
{
Console.WriteLine("接收消息错误:"+e.ErrorCode+","+e.Message);
}
}
public void Send(String str)
{
if (this.socket.Connected)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
this.socket.BeginSend(bytes,0,bytes.Length,SocketFlags.None,SendCallback,this.socket);
}
else
{
Console.WriteLine("没有链接,能收消息");
}
}
private void SendCallback(IAsyncResult result)
{
try
{
this.socket.EndSend(result);
}
catch (SocketException e)
{
Console.WriteLine("发送失败:"+e.ErrorCode+","+e.Message);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class SeverSocket
{
Socket socket;
private Dictionary<int, ClientSocket> clientDic = new Dictionary<int, ClientSocket>();

public void Start(String ip, int port, int num)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);

try
{
socket.Bind(ipPoint);
socket.Listen(num);
//通过异步接收客户端连入
socket.BeginAccept(AcceptCallback,socket);
}
catch (Exception e)
{
Console.WriteLine("启动服务器失败"+e.Message);

}

}
private void AcceptCallback(IAsyncResult result)
{
try
{
//获取连入的客户端
Socket clientSocket = socket.EndAccept(result);
ClientSocket client = new ClientSocket(clientSocket);
//记录客户端对象
clientDic.Add(client.clientId, client);
//继续让客户端连入
socket.BeginAccept(AcceptCallback,socket);
}
catch (Exception e)
{
Console.WriteLine("客户端连入失败:"+e.Message);
}
}
public void Broadcast(string str)
{
foreach (ClientSocket client in clientDic.Values)
{
client.Send(str);
}
}
}

评论