ScanSocket.cs
3.2 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 扫码枪连接类
/// </summary>
public class ScanSocket
{
private readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event ScanRevice OnScanRevice;
public delegate void ScanRevice(string message);
/// <summary>
/// 扫码枪链接
/// </summary>
private TcpClient scannerSocket;
/// <summary>
/// 扫描枪 是否开始运行
/// </summary>
public bool isScannerRun = false;
/// <summary>
/// 连接扫码枪
/// </summary>
/// <param name="serverIp">扫码枪Ip</param>
/// <param name="port">扫码枪端口号</param>
/// <returns>是否连接成功</returns>
public bool ConnectScanner(string serverIp, int port)
{
return StartScanner(serverIp, port, false);
}
/// <summary>
/// 停止扫码枪
/// </summary>
public void StopScanner()
{
try
{
scannerSocket.close();
isScannerRun = false;
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
}
/// <summary>
/// 发送扫码命令开始扫码
/// </summary>
public void BeginScannering()
{
string str = ConfigAppSettings.GetValue(Setting_Init.scanner_start_command);
if (str.Equals(""))
{
str = "S";
}
scannerSocket.send(str);
//onCodeReceived("AAAA");
}
/// <summary>
/// 开启扫码枪
/// </summary>
private bool StartScanner(string serverIp, int port, bool isMustCon)
{
bool result = true;
try
{
if (!isScannerRun || isMustCon)
{
if (scannerSocket == null)
{
scannerSocket = new TcpClient();
}
result = scannerSocket.connect(serverIp, port, new TcpClient.HandleMessage(onCodeReceived));
if (result)
{
isScannerRun = true;
}
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
return result;
}
/// <summary>
/// 扫码枪数据接收
/// </summary>
/// <param name="message"></param>
private void onCodeReceived(string message)
{
try
{
message = ScanCodeManager.ReplaceCode(message);
if (OnScanRevice != null)
{
OnScanRevice.Invoke(message);
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex.ToString());
}
}
}
}