SocketClient.cs
2.88 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
using HHECS.Bll;
using HHECS.Model.Enums;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace HHECS.Scan
{
public class SocketClient
{
private Socket socket;
private IPEndPoint endPoint;
private byte[] buffer = new byte[1024];
/// <summary>
/// 构造函数
/// </summary>
/// <param name="ip">连接服务器的IP</param>
/// <param name="port">连接服务器的端口</param>
public SocketClient(string ip, int port)
{
try
{
// 创建IP对象
IPAddress address = IPAddress.Parse(ip);
// 创建网络端口包括ip和端口
this.endPoint = new IPEndPoint(address, port);
// 实例化套接字(IP4寻址地址,流式传输,TCP协议)
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
catch (Exception ex)
{
Logger.Log(ex.Message, LogLevel.Exception);
}
}
/// <summary>
/// 建立连接
/// </summary>
public void connect()
{
try
{
this.socket.Connect(endPoint);
}
catch (Exception ex)
{
Logger.Log(ex.Message, LogLevel.Exception);
}
}
/// <summary>
/// 判断socket是否连接
/// </summary>
public bool Connected()
{
bool connected = false;
try
{
connected = this.socket.Connected;
}
catch (Exception ex)
{
Logger.Log(ex.Message, LogLevel.Exception);
}
return connected;
}
/// <summary>
/// 获取条码
/// </summary>
public string getBarcode()
{
string result = "";
try
{
// 向服务器发送消息
byte[] data = Encoding.UTF8.GetBytes("8000");
socket.Send(data);
// 接收数据
System.Threading.Thread.Sleep(10);
int length = socket.Receive(buffer);
result = Encoding.UTF8.GetString(buffer, 0, length);
}
catch (Exception ex)
{
Logger.Log(ex.Message, LogLevel.Exception);
}
return result;
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
try
{
this.socket.Shutdown(SocketShutdown.Both);
this.socket.Close();
}
catch (Exception ex)
{
Logger.Log(ex.Message, LogLevel.Exception);
}
}
}
}