67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Threading;
|
|
|
|
namespace 常用工具集.Utility.Network
|
|
{
|
|
public class SocketHelper
|
|
{
|
|
|
|
//1.声明关于事件的委托;
|
|
public delegate void MessageEventHandler(object sender, byte[] bytesList);
|
|
//2.声明事件;
|
|
public event MessageEventHandler MessageHandler;
|
|
|
|
private TimeOutSocket socket;
|
|
private string ipAddress;
|
|
private int port;
|
|
|
|
public SocketHelper(string ipAddress, int port)
|
|
{
|
|
this.ipAddress = ipAddress;
|
|
this.port = port;
|
|
socket = new TimeOutSocket(ipAddress, port, 1000);
|
|
}
|
|
public SocketHelper()
|
|
{
|
|
}
|
|
|
|
public void SendAsyn(string ipAddress, int port, byte[] bytes)
|
|
{
|
|
new Thread(() =>
|
|
{
|
|
|
|
try
|
|
{
|
|
byte[] retBytes = new byte[1024];
|
|
TimeOutSocket socket = new TimeOutSocket(ipAddress, port, 1000);
|
|
TcpClient client = socket.Connect();
|
|
client.SendTimeout = 1000;
|
|
client.ReceiveTimeout = 1000;
|
|
NetworkStream ns = client.GetStream();
|
|
ns.Write(bytes, 0, bytes.Length);
|
|
Thread.Sleep(250);
|
|
int length = ns.Read(retBytes, 0, retBytes.Length);
|
|
ns.Close();
|
|
client.Close();
|
|
byte[] newRetBytes = new byte[length];
|
|
for (int i = 0; i < length; i++)
|
|
newRetBytes[i] = retBytes[i];
|
|
MessageHandler?.Invoke(this, newRetBytes);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
byte[] retBytes = new byte[1];
|
|
retBytes[0] = 0x00;
|
|
MessageHandler?.Invoke(this, retBytes);
|
|
}
|
|
}).Start();
|
|
|
|
}
|
|
}
|
|
}
|