Skip to content
切换导航条
切换导航条
当前项目
正在载入...
登录
孙克
/
URSolderingRobot
转到一个项目
切换导航栏
切换导航栏固定状态
项目
群组
代码片段
帮助
项目
活动
版本库
流水线
图表
问题
0
合并请求
0
维基
网络
创建新的问题
作业
提交
问题看板
文件
提交
网络
比较
分支
标签
Commit 07b72b9c
由
几米阳光
编写于
2018-08-01 14:10:13 +0800
浏览文件
选项
浏览文件
标签
下载
电子邮件补丁
差异文件
机器人调试修改
1 个父辈
55b8cbcc
隐藏空白字符变更
内嵌
并排
正在显示
8 个修改的文件
包含
386 行增加
和
84 行删除
Common/Common.csproj
Common/logs/LogUtil.cs
Common/util/TcpClient.cs
Common/util/URTcpClient.cs
DeviceLibrary/DeviceLibrary.csproj
DeviceLibrary/deviceLibrary/urRobot/URRobotClient.cs
DeviceLibrary/deviceLibrary/urRobot/URRobotControl.cs
DeviceLibrary/deviceLibrary/urRobot/URTcpClient.cs
Common/Common.csproj
查看文件 @
07b72b9
...
...
@@ -95,7 +95,6 @@
<Compile Include="util\AcSerialBean.cs" />
<Compile Include="util\SerialBean.cs" />
<Compile Include="util\StringUtil.cs" />
<Compile Include="util\URTcpClient.cs" />
<Compile Include="util\TcpClient.cs" />
<Compile Include="util\TcpServer.cs" />
<Compile Include="util\WaitUtil.cs" />
...
...
Common/logs/LogUtil.cs
查看文件 @
07b72b9
...
...
@@ -188,7 +188,10 @@ namespace URSoldering.Common
{
urListenLog
.
Error
(
msg
);
}
public
static
void
URLDebug
(
string
msg
)
{
urListenLog
.
Debug
(
msg
);
}
/// <summary>
...
...
Common/util/TcpClient.cs
查看文件 @
07b72b9
...
...
@@ -15,14 +15,12 @@ namespace URSoldering.Common
{
public
static
readonly
ILog
LOGGER
=
LogManager
.
GetLogger
(
MethodBase
.
GetCurrentMethod
().
DeclaringType
);
public
delegate
void
HandleMessage
(
string
message
);
public
delegate
void
ByteHandleMessage
(
byte
[]
data
);
public
int
DefaultDataLength
=
1024
;
public
int
ReviceSleepMS
=
100
;
private
Socket
m_clientSocket
=
null
;
public
int
DefaultDataLength
=
1024
;
public
int
ReviceSleepMS
=
100
;
private
Socket
m_clientSocket
=
null
;
private
byte
[]
m_receiveBuffer
=
new
byte
[
1024
];
private
string
LogName
=
""
;
private
HandleMessage
onReceived
;
private
ByteHandleMessage
byteOnReceived
;
public
int
TimeOutTime
=
0
;
/// <summary>
...
...
@@ -91,20 +89,14 @@ namespace URSoldering.Common
return
false
;
}
}
public
bool
connect
(
string
serverIP
,
int
serverPort
,
ByteHandleMessage
byteHandle
)
{
return
connect
(
serverIP
,
serverPort
,
null
,
byteHandle
);
}
/// <summary>
/// 连接服务器
/// </summary>
public
bool
connect
(
string
serverIP
,
int
serverPort
,
HandleMessage
HandleMessage
)
{
return
connect
(
serverIP
,
serverPort
,
HandleMessage
,
null
);
}
/// <summary>
/// 连接服务器
/// </summary>
private
bool
connect
(
string
serverIP
,
int
serverPort
,
HandleMessage
HandleMessage
,
ByteHandleMessage
byteHandle
)
{
LogName
=
"【"
+
serverIP
+
" ,"
+
serverPort
+
"】"
;
m_receiveBuffer
=
new
byte
[
DefaultDataLength
];
m_clientSocket
=
new
Socket
(
AddressFamily
.
InterNetwork
,
SocketType
.
Stream
,
ProtocolType
.
Tcp
);
if
(
TimeOutTime
<=
0
)
...
...
@@ -124,21 +116,18 @@ namespace URSoldering.Common
{
onReceived
=
HandleMessage
;
}
if
(
byteHandle
!=
null
)
{
byteOnReceived
=
byteHandle
;
}
LogUtil
.
info
(
LOGGER
,
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" success!"
);
LogUtil
.
info
(
LOGGER
,
LogName
+
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" success!"
);
return
true
;
}
else
{
LogUtil
.
info
(
LOGGER
,
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
);
LogUtil
.
info
(
LOGGER
,
LogName
+
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
);
}
}
catch
(
Exception
ex
)
{
LogUtil
.
error
(
LOGGER
,
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
+
ex
.
ToString
(),
3
);
LogUtil
.
error
(
LOGGER
,
LogName
+
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
+
ex
.
ToString
(),
3
);
//m_clientSocket = null;
}
}
...
...
@@ -150,26 +139,23 @@ namespace URSoldering.Common
connResult
.
AsyncWaitHandle
.
WaitOne
(
this
.
TimeOutTime
,
true
);
//等待2秒
if
(!
connResult
.
IsCompleted
||
(!
m_clientSocket
.
Connected
))
if
(!
connResult
.
IsCompleted
||
(!
m_clientSocket
.
Connected
))
{
LogUtil
.
info
(
LOGGER
,
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
);
LogUtil
.
info
(
LOGGER
,
LogName
+
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" fail!"
);
m_clientSocket
.
Close
();
//处理连接不成功的动作
return
false
;
}
else
{
{
//处理连接成功的动作
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
if
(
HandleMessage
!=
null
)
{
onReceived
=
HandleMessage
;
}
if
(
byteHandle
!=
null
)
{
byteOnReceived
=
byteHandle
;
}
LogUtil
.
info
(
LOGGER
,
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" success!"
);
LogUtil
.
info
(
LOGGER
,
LogName
+
"Connect to "
+
serverIP
+
":"
+
serverPort
+
" success!"
);
return
true
;
}
}
...
...
@@ -183,20 +169,21 @@ namespace URSoldering.Common
{
try
{
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Shutdown
(
SocketShutdown
.
Both
);
m_clientSocket
.
Close
();
LogUtil
.
info
(
LOGGER
,
"Socket closed!"
);
m_clientSocket
.
Shutdown
(
SocketShutdown
.
Both
);
m_clientSocket
.
Close
();
LogUtil
.
info
(
LOGGER
,
LogName
+
"Socket closed!"
);
}
else
{
LogUtil
.
error
(
LOGGER
,
"No socket is running!"
);
LogUtil
.
error
(
LOGGER
,
LogName
+
"No socket is running!"
);
}
m_clientSocket
=
null
;
}
catch
(
Exception
ex
)
{
LogUtil
.
error
(
LOGGER
,
"close error :"
+
ex
.
ToString
());
LogUtil
.
error
(
LOGGER
,
LogName
+
"close error :"
+
ex
.
ToString
());
}
}
...
...
@@ -211,7 +198,7 @@ namespace URSoldering.Common
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Send
(
sendBuffer
);
LogUtil
.
debug
(
LOGGER
,
"Send >> "
+
strSendData
);
LogUtil
.
debug
(
LOGGER
,
LogName
+
"Send >> "
+
strSendData
);
}
}
/// <summary>
...
...
@@ -219,27 +206,20 @@ namespace URSoldering.Common
/// </summary>
public
void
sendLine
(
string
strSendData
)
{
if
(
strSendData
.
StartsWith
(
"save"
))
{
LogUtil
.
debug
(
LOGGER
,
"发送数据:"
+
strSendData
);
}
else
{
LogUtil
.
debug
(
LOGGER
,
"发送数据:"
+
strSendData
);
}
strSendData
=
strSendData
+
"\r\n"
;
byte
[]
sendBuffer
=
new
byte
[
DefaultDataLength
];
sendBuffer
=
Encoding
.
UTF8
.
GetBytes
(
strSendData
);
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Send
(
sendBuffer
);
LogUtil
.
debug
(
LOGGER
,
"Send >> "
+
strSendData
);
LogUtil
.
debug
(
LOGGER
,
LogName
+
"Send >> "
+
strSendData
);
}
}
private
void
ReceiveCallBack
(
IAsyncResult
ar
)
{
try
...
...
@@ -247,17 +227,18 @@ namespace URSoldering.Common
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
int
REnd
=
m_clientSocket
.
EndReceive
(
ar
);
byteOnReceived
?.
Invoke
(
m_receiveBuffer
);
string
strReceiveData
=
Encoding
.
Default
.
GetString
(
m_receiveBuffer
,
0
,
REnd
);
onReceived
?.
Invoke
(
strReceiveData
);
onReceived
?.
Invoke
(
strReceiveData
);
Thread
.
Sleep
(
ReviceSleepMS
);
//LOGGER.Debug("m_clientSocket:" + m_clientSocket + "\n m_receiveBuffer" + m_receiveBuffer);
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
}
}
}
catch
(
Exception
ex
)
{
LogUtil
.
error
(
LOGGER
,
"socket received error:"
+
ex
.
ToString
(),
4
);
LogUtil
.
error
(
LOGGER
,
LogName
+
"socket received error:"
+
ex
.
ToString
(),
4
);
}
}
}
...
...
Common/util/URTcpClient.cs
查看文件 @
07b72b9
...
...
@@ -107,7 +107,7 @@ namespace URSoldering.Common
{
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
byteOnReceived
=
byteHandle
;
LogUtil
.
URL
Info
(
"Connect to "
+
LogName
+
" success"
);
LogUtil
.
URL
Debug
(
"Connect to "
+
LogName
+
" success"
);
return
true
;
}
else
...
...
@@ -161,7 +161,7 @@ namespace URSoldering.Common
{
m_clientSocket
.
Shutdown
(
SocketShutdown
.
Both
);
m_clientSocket
.
Close
();
LogUtil
.
URL
Info
(
LogName
+
"Socket closed!"
);
LogUtil
.
URL
Debug
(
LogName
+
"Socket closed!"
);
}
else
{
...
...
@@ -309,11 +309,11 @@ namespace URSoldering.Common
{
byteOnReceived
(
m_receiveBuffer
);
});
Thread
.
Sleep
(
ReviceSleepMS
);
//
Thread.Sleep(ReviceSleepMS);
//LOGGER.Debug("m_clientSocket:" + m_clientSocket + "\n m_receiveBuffer" + m_receiveBuffer);
//Task.Factory.StartNew(delegate ()
//{
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
//
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
//});
}
}
...
...
DeviceLibrary/DeviceLibrary.csproj
查看文件 @
07b72b9
...
...
@@ -98,6 +98,7 @@
<Compile Include="deviceLibrary\kangnaide\MasterTcpClient.cs" />
<Compile Include="deviceLibrary\urRobot\URRobotControl.cs" />
<Compile Include="deviceLibrary\urRobot\URRobotClient.cs" />
<Compile Include="deviceLibrary\urRobot\URTcpClient.cs" />
<Compile Include="Robot\MoveType.cs" />
<Compile Include="Robot\soldering\AlarmType.cs" />
<Compile Include="bean\BoardManager.cs" />
...
...
DeviceLibrary/deviceLibrary/urRobot/URRobotClient.cs
查看文件 @
07b72b9
...
...
@@ -70,20 +70,17 @@ namespace URSoldering.DeviceLibrary
if
(
LastMoveCMD
.
Equals
(
""
).
Equals
(
false
))
{
listenClient
.
sendLine
(
LastMoveCMD
);
LastMoveCMD
=
""
;
//Thread.Sleep(50);
LastMoveCMD
=
""
;
}
StopListen
();
try
{
//string reviceMsg = ByteToStr(reviceData);
//LogUtil.info("Read data:【" + reviceMsg + "】 ");
{
byte
[]
msgSizeArray
=
reviceData
.
Skip
(
0
).
Take
(
4
).
ToArray
();
byte
[]
timeArray
=
reviceData
.
Skip
(
4
).
Take
(
8
).
ToArray
();
byte
[]
qTargetArray
=
reviceData
.
Skip
(
12
).
Take
(
48
).
ToArray
();
byte
[]
qdTargetArray
=
reviceData
.
Skip
(
60
).
Take
(
48
).
ToArray
();
byte
[]
qddArray
=
reviceData
.
Skip
(
108
).
Take
(
48
).
ToArray
();
byte
[]
iTargetArray
=
reviceData
.
Skip
(
156
).
Take
(
48
).
ToArray
();
//
byte[] timeArray = reviceData.Skip(4).Take(8).ToArray();
//
byte[] qTargetArray = reviceData.Skip(12).Take(48).ToArray();
//
byte[] qdTargetArray = reviceData.Skip(60).Take(48).ToArray();
//
byte[] qddArray = reviceData.Skip(108).Take(48).ToArray();
//
byte[] iTargetArray = reviceData.Skip(156).Take(48).ToArray();
int
messageSize
=
BitToInt
(
reviceData
.
Skip
(
0
).
Take
(
4
).
ToArray
().
Reverse
<
byte
>().
ToArray
());
int
maxdouble
=
(
messageSize
-
4
)
/
8
;
...
...
@@ -113,8 +110,7 @@ namespace URSoldering.DeviceLibrary
}
}
if
(
doubleList
.
Count
>
61
)
{
string
spilt
=
","
;
{
double
x
=
doubleList
[
56
]
*
1000
;
double
y
=
doubleList
[
57
]
*
1000
;
double
z
=
doubleList
[
58
]
*
1000
;
...
...
@@ -122,16 +118,18 @@ namespace URSoldering.DeviceLibrary
double
ry
=
doubleList
[
60
]
*
1
;
double
rz
=
doubleList
[
61
]
*
1
;
URPointValue
newp
=
new
URPointValue
(
x
,
y
,
z
,
rx
,
ry
,
rz
);
//string reviceMsg = ByteToStr(reviceData);
if
(!
URRobotControl
.
IsSamePoint
(
newp
,
URRobotControl
.
LastPoint
))
{
LogUtil
.
URLInfo
(
LogName
+
"length["
+
messageSize
+
"],data长["
+
reviceData
.
Length
+
"]坐标"
+
newp
.
ToShowStr
());
}
URRobotControl
.
LastPoint
=
newp
;
string
reviceMsg
=
ByteToStr
(
reviceData
);
//LogUtil.info("Read data:【" + reviceMsg + "】 ");
LogUtil
.
URLInfo
(
LogName
+
"length["
+
messageSize
+
"],data长["
+
reviceData
.
Length
+
"]坐标"
+
newp
.
ToShowStr
());
}
}
else
{
string
reviceMsg
=
ByteToStr
(
reviceData
);
//LogUtil.URLError(LogName + "Read data:【" + reviceMsg + "】 ");
string
reviceMsg
=
ByteToStr
(
reviceData
);
LogUtil
.
URLError
(
LogName
+
"length["
+
messageSize
+
"],data长["
+
reviceData
.
Length
+
"]无法获取坐标,数据长度不正确"
);
}
}
...
...
DeviceLibrary/deviceLibrary/urRobot/URRobotControl.cs
查看文件 @
07b72b9
...
...
@@ -124,7 +124,7 @@ namespace URSoldering.DeviceLibrary
{
reconnectTimer
=
new
System
.
Timers
.
Timer
();
reconnectTimer
.
AutoReset
=
true
;
reconnectTimer
.
Interval
=
10
00
;
reconnectTimer
.
Interval
=
4
00
;
reconnectTimer
.
Elapsed
+=
reconnectTimer_Elapsed
;
reconnectTimer
.
Enabled
=
false
;
}
...
...
@@ -199,7 +199,7 @@ namespace URSoldering.DeviceLibrary
if
(
IsRun
&&
IsStartConnect
)
{
TimeSpan
span
=
DateTime
.
Now
-
preCheckTime
;
if
(
span
.
TotalSeconds
>
30
)
if
(
span
.
TotalSeconds
>
2
)
{
preCheckTime
=
DateTime
.
Now
;
//判断500在连接上,则获取急停状态
...
...
@@ -415,7 +415,7 @@ namespace URSoldering.DeviceLibrary
{
IsRun
=
false
;
startCount
--;
controlTcp
.
sendLine
(
CMD_powerOff
);
//
controlTcp.sendLine(CMD_powerOff);
controlTcp
.
close
();
}
catch
(
Exception
ex
)
...
...
@@ -429,9 +429,10 @@ namespace URSoldering.DeviceLibrary
public
static
void
StopRobot
()
{
try
{
{
IsStartConnect
=
false
;
reconnectTimer
.
Enabled
=
false
;
URRobotClient
.
StopListen
();
stopTcp
();
}
catch
(
Exception
ex
)
...
...
@@ -507,7 +508,7 @@ namespace URSoldering.DeviceLibrary
}
}
return
false
;
}
p
rivate
static
bool
IsSamePoint
(
URPointValue
p1
,
URPointValue
p2
)
p
ublic
static
bool
IsSamePoint
(
URPointValue
p1
,
URPointValue
p2
)
{
if
(
p1
==
null
&&
p2
==
null
)
{
...
...
@@ -519,7 +520,7 @@ namespace URSoldering.DeviceLibrary
double
rxCha
=
Math
.
Abs
(
p1
.
RX
-
p2
.
RX
);
double
ryCha
=
Math
.
Abs
(
p1
.
RY
-
p2
.
RY
);
double
rzCha
=
Math
.
Abs
(
p1
.
RZ
-
p2
.
RZ
);
if
(
xCha
<
1
&&
yCha
<
1
&&
zCha
<
1
&&
rxCha
<
0.0
1
&&
ryCha
<
0.01
&&
rzCha
<
0.01
)
if
(
xCha
<
1
&&
yCha
<
1
&&
zCha
<
1
&&
rxCha
<
0.0
2
&&
ryCha
<
0.02
&&
rzCha
<
0.02
)
{
return
true
;
}
...
...
DeviceLibrary/deviceLibrary/urRobot/URTcpClient.cs
0 → 100644
查看文件 @
07b72b9
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Text
;
using
System.Net
;
using
System.Net.Sockets
;
using
log4net
;
using
System.Reflection
;
using
System.Threading
;
using
System.Threading.Tasks
;
using
URSoldering.Common
;
namespace
URSoldering.DeviceLibrary
{
public
class
URTcpClient
{
public
delegate
void
ByteHandleMessage
(
byte
[]
data
);
public
int
DefaultDataLength
=
1078
;
public
int
ReviceSleepMS
=
100
;
private
Socket
m_clientSocket
=
null
;
private
byte
[]
m_receiveBuffer
=
new
byte
[
1078
];
private
string
LogName
=
""
;
private
ByteHandleMessage
byteOnReceived
;
public
int
TimeOutTime
=
0
;
/// <summary>
/// 当前连接状态
/// </summary>
public
bool
IsConnected
()
{
if
(
m_clientSocket
==
null
)
{
return
false
;
}
if
(
m_clientSocket
.
Connected
)
{
return
true
;
}
try
{
#
region
过程
// This is how you can determine whether a socket is still connected.
bool
connectState
=
true
;
bool
blockingState
=
m_clientSocket
.
Blocking
;
try
{
byte
[]
tmp
=
new
byte
[
1
];
m_clientSocket
.
Blocking
=
false
;
m_clientSocket
.
Send
(
tmp
,
0
,
0
);
//Console.WriteLine("Connected!");
connectState
=
true
;
//若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
}
catch
(
SocketException
e
)
{
// 10035 == WSAEWOULDBLOCK
if
(
e
.
NativeErrorCode
.
Equals
(
10035
))
{
connectState
=
true
;
}
else
{
connectState
=
false
;
}
}
finally
{
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Blocking
=
blockingState
;
}
}
return
connectState
;
#
endregion
}
catch
(
Exception
ex
)
{
LogUtil
.
debug
(
LogName
+
"出错啦"
+
ex
.
ToString
());
return
false
;
}
}
/// <summary>
/// 连接服务器
/// </summary>
public
bool
connect
(
string
serverIP
,
int
serverPort
,
ByteHandleMessage
byteHandle
)
{
LogName
=
"【"
+
serverIP
+
" ,"
+
serverPort
+
"】"
;
m_receiveBuffer
=
new
byte
[
DefaultDataLength
];
m_clientSocket
=
new
Socket
(
AddressFamily
.
InterNetwork
,
SocketType
.
Stream
,
ProtocolType
.
Tcp
);
if
(
TimeOutTime
<=
0
)
{
IPEndPoint
remoteEndPoint
=
new
IPEndPoint
(
IPAddress
.
Parse
(
serverIP
),
serverPort
);
m_clientSocket
.
SetSocketOption
(
SocketOptionLevel
.
Socket
,
SocketOptionName
.
ReuseAddress
,
true
);
try
{
if
(!
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Connect
(
remoteEndPoint
);
}
if
(
m_clientSocket
.
Connected
)
{
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
byteOnReceived
=
byteHandle
;
LogUtil
.
URLDebug
(
LogName
+
"Connect to "
+
LogName
+
" success"
);
return
true
;
}
else
{
LogUtil
.
URLInfo
(
LogName
+
"Connect to "
+
LogName
+
" fail"
);
}
}
catch
(
Exception
ex
)
{
LogUtil
.
URLError
(
LogName
+
"Connect to "
+
LogName
+
" error :"
+
ex
.
ToString
());
}
}
else
{
m_clientSocket
.
ReceiveTimeout
=
TimeOutTime
;
m_clientSocket
.
SendTimeout
=
TimeOutTime
;
IAsyncResult
connResult
=
m_clientSocket
.
BeginConnect
(
serverIP
,
serverPort
,
null
,
null
);
connResult
.
AsyncWaitHandle
.
WaitOne
(
this
.
TimeOutTime
,
true
);
//等待2秒
if
(!
connResult
.
IsCompleted
||
(!
m_clientSocket
.
Connected
))
{
LogUtil
.
URLInfo
(
LogName
+
"Connect to "
+
LogName
+
" fail"
);
m_clientSocket
.
Close
();
//处理连接不成功的动作
return
false
;
}
else
{
//处理连接成功的动作
m_clientSocket
.
BeginReceive
(
m_receiveBuffer
,
0
,
m_receiveBuffer
.
Length
,
0
,
new
AsyncCallback
(
ReceiveCallBack
),
null
);
byteOnReceived
=
byteHandle
;
if
(
byteHandle
!=
null
)
{
byteOnReceived
=
byteHandle
;
}
LogUtil
.
URLInfo
(
LogName
+
"Connect to "
+
LogName
+
" success"
);
return
true
;
}
}
return
false
;
}
/// <summary>
/// 断开连接
/// </summary>
public
void
close
()
{
try
{
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Shutdown
(
SocketShutdown
.
Both
);
m_clientSocket
.
Close
();
LogUtil
.
URLDebug
(
LogName
+
"Socket closed!"
);
}
else
{
LogUtil
.
URLInfo
(
LogName
+
"No socket is running!"
);
}
m_clientSocket
=
null
;
}
catch
(
Exception
ex
)
{
LogUtil
.
URLError
(
LogName
+
"close error :"
+
ex
.
ToString
());
}
}
/// <summary>
/// 发送信息
/// </summary>
public
void
send
(
string
strSendData
)
{
byte
[]
sendBuffer
=
new
byte
[
DefaultDataLength
];
sendBuffer
=
Encoding
.
UTF8
.
GetBytes
(
strSendData
);
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Send
(
sendBuffer
);
LogUtil
.
debug
(
LogName
+
"Send >> "
+
strSendData
);
}
}
/// <summary>
/// 发送信息
/// </summary>
public
void
sendLine
(
string
strSendData
)
{
try
{
LogUtil
.
info
(
LogName
+
"发送数据:"
+
strSendData
);
LogUtil
.
URLInfo
(
LogName
+
"发送数据:"
+
strSendData
);
strSendData
=
strSendData
+
"\r\n"
;
byte
[]
sendBuffer
=
new
byte
[
DefaultDataLength
];
sendBuffer
=
Encoding
.
UTF8
.
GetBytes
(
strSendData
);
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
m_clientSocket
.
Send
(
sendBuffer
);
}
}
catch
(
Exception
ex
)
{
LogUtil
.
error
(
LogName
+
"发送数据【"
+
strSendData
+
"】出错"
);
LogUtil
.
URLError
(
LogName
+
"发送数据【"
+
strSendData
+
"】出错:"
+
ex
.
ToString
());
}
}
int
headSize
=
4
;
//包头长度 固定4
byte
[]
surplusBuffer
=
null
;
//不完整的数据包,即用户自定义缓冲区
/// <summary>
/// 接收客户端发来的数据
/// </summary>
/// <param name="connId">每个客户的会话ID</param>
/// <param name="bytes">缓冲区数据</param>
/// <returns></returns>
private
int
OnReceive
(
byte
[]
bytes
)
{
try
{
//bytes 为系统缓冲区数据
//bytesRead为系统缓冲区长度
int
bytesRead
=
bytes
.
Length
;
if
(
bytesRead
>
0
)
{
if
(
surplusBuffer
==
null
)
//判断是不是第一次接收,为空说是第一次
{
surplusBuffer
=
bytes
;
//把系统缓冲区数据放在自定义缓冲区里面
}
else
{
surplusBuffer
=
surplusBuffer
.
Concat
(
bytes
).
ToArray
();
//拼接上一次剩余的包
}
//已经完成读取每个数据包长度
int
haveRead
=
0
;
//这里totalLen的长度有可能大于缓冲区大小的(因为 这里的surplusBuffer 是系统缓冲区+不完整的数据包)
int
totalLen
=
surplusBuffer
.
Length
;
while
(
haveRead
<=
totalLen
)
{
//如果在N此拆解后剩余的数据包连一个包头的长度都不够
//说明是上次读取N个完整数据包后,剩下的最后一个非完整的数据包
if
(
totalLen
-
haveRead
<
headSize
)
{
byte
[]
byteSub
=
new
byte
[
totalLen
-
haveRead
];
//把剩下不够一个完整的数据包存起来
Buffer
.
BlockCopy
(
surplusBuffer
,
haveRead
,
byteSub
,
0
,
totalLen
-
haveRead
);
surplusBuffer
=
byteSub
;
totalLen
=
0
;
break
;
}
//如果够了一个完整包,则读取包头的数据
byte
[]
headByte
=
new
byte
[
headSize
];
Buffer
.
BlockCopy
(
surplusBuffer
,
haveRead
,
headByte
,
0
,
headSize
);
//从缓冲区里读取包头的字节
headByte
=
surplusBuffer
.
Skip
(
haveRead
).
Take
(
headSize
).
ToArray
().
Reverse
<
byte
>().
ToArray
();
int
bodySize
=
BitConverter
.
ToInt32
(
headByte
,
0
);
//从包头里面分析出包体的长度
if
(
bodySize
<=
0
)
{
LogUtil
.
URLError
(
LogName
+
"解析错误:长度:"
+
bodySize
);
}
//这里的 haveRead=等于N个数据包的长度 从0开始;0,1,2,3....N
//如果自定义缓冲区拆解N个包后的长度 大于 总长度,说最后一段数据不够一个完整的包了,拆出来保存
if
(
haveRead
+
bodySize
>
totalLen
)
{
byte
[]
byteSub
=
new
byte
[
totalLen
-
haveRead
];
Buffer
.
BlockCopy
(
surplusBuffer
,
haveRead
,
byteSub
,
0
,
totalLen
-
haveRead
);
surplusBuffer
=
byteSub
;
break
;
}
else
{
//挨个分解每个包,解析成实际文字
byte
[]
endArray
=
surplusBuffer
.
Skip
(
haveRead
).
Take
(
bodySize
).
ToArray
();
//
Task
.
Factory
.
StartNew
(
delegate
()
{
byteOnReceived
?.
Invoke
(
endArray
);
});
//依次累加当前的数据包的长度
haveRead
=
haveRead
+
bodySize
;
if
(
bodySize
==
bytesRead
)
//如果当前接收的数据包长度正好等于缓冲区长度,则待拼接的不规则数据长度归0
{
surplusBuffer
=
null
;
//设置空 回到原始状态
totalLen
=
0
;
//清0
}
}
}
}
}
catch
(
Exception
ex
)
{
LogUtil
.
URLError
(
LogName
+
" 分包出错:"
+
ex
.
ToString
());
}
return
1
;
}
private
void
ReceiveCallBack
(
IAsyncResult
ar
)
{
try
{
if
(
m_clientSocket
!=
null
&&
m_clientSocket
.
Connected
)
{
int
REnd
=
m_clientSocket
.
EndReceive
(
ar
);
Task
.
Factory
.
StartNew
(
delegate
()
{
byteOnReceived
(
m_receiveBuffer
);
});
//m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
}
catch
(
Exception
ex
)
{
LogUtil
.
URLError
(
LogName
+
" socket received error:"
+
ex
.
ToString
());
}
}
}
}
编写
预览
支持
Markdown
格式
附加文件
你添加了
0
人
到此讨论。请谨慎行事。
Finish editing this message first!
Cancel
请
注册
或
登录
后发表评论