-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientSocket.cs
More file actions
99 lines (90 loc) · 3.14 KB
/
Copy pathClientSocket.cs
File metadata and controls
99 lines (90 loc) · 3.14 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketTest.Common
{
/// <summary>
/// Copyright (C) 2017 yjq 版权所有。
/// 类名:ClientSocket.cs
/// 类属性:公共类(非静态)
/// 类功能描述:
/// 创建标识:yjq 2017/11/22 11:46:13
/// </summary>
public class ClientSocket
{
private Socket _socket;
private AutoResetEvent _autoResetEvent;
private TcpConnetion _tcpConnetion;
private IPEndPoint _hostIPEndPoint;
private Action<TcpConnetion, byte[]> _messageArrivedHandler;
private SocketSetting _socketSetting;
public ClientSocket(IPEndPoint iPEndPoint, SocketSetting socketSetting, Action<TcpConnetion, byte[]> messageArrivedHandler)
{
_socket = SocketUtil.Create(socketSetting.ReceiveBufferSize, socketSetting.SendBufferSize);
_autoResetEvent = new AutoResetEvent(false);
_hostIPEndPoint = iPEndPoint;
_messageArrivedHandler = messageArrivedHandler;
_socketSetting = socketSetting;
}
public bool IsConnected
{
get { return _tcpConnetion != null && _tcpConnetion.IsConnected; }
}
public TcpConnetion Connection
{
get { return _tcpConnetion; }
}
public ClientSocket Start()
{
var connectArgs = new SocketAsyncEventArgs();
connectArgs.AcceptSocket = _socket;
connectArgs.RemoteEndPoint = _hostIPEndPoint;
connectArgs.Completed += ConnectArgs_Completed;
var willRaiseEvent = _socket.ConnectAsync(connectArgs);
if (!willRaiseEvent)
{
ProcessConnect(connectArgs);
}
_autoResetEvent.WaitOne();
return this;
}
private void ConnectArgs_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessConnect(e);
}
private void ProcessConnect(SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
LogUtil.Warn("连接服务端失败");
_socket.ShutDownCurrent();
_autoResetEvent.Set();
return;
}
LogUtil.Info("连接服务端成功");
_tcpConnetion = new TcpConnetion(_socket, MessageArrived, _socketSetting);
_autoResetEvent.Set();
}
public void SendMessage(byte[] messageBytes)
{
_tcpConnetion.SendMessage(messageBytes);
}
private void MessageArrived(TcpConnetion tcpConnetion, byte[] messageBytes)
{
try
{
_messageArrivedHandler?.Invoke(tcpConnetion, messageBytes);
LogUtil.Info($"接收来自客户端发送的信息:{tcpConnetion.RemotingEndPoint}:【{Encoding.UTF8.GetString(messageBytes)}】");
}
catch (Exception e)
{
LogUtil.Error(e);
}
}
}
}