You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
6.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace SocketProcess
{
public class SocketServer
{
public ManualResetEvent allDone = new ManualResetEvent(false);
public List<StateObject> ListenerList = new List<StateObject>();
Socket listener;
public delegate void delRecive(string barcode, object o);
public delRecive ReciveEvent;
public SocketServer()
{
}
/// <summary>
///
/// </summary>
public void StartService(int port)
{
byte[] bytes = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
//Mesnac.Log.LogService.Instance.Debug("开始服务,等待客户端连接");
listener.BeginAccept(AcceptCallback, listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
// Mesnac.Log.LogService.Instance.Debug("开始服务出错:"+e.ToString());
}
}
public void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//Mesnac.Log.LogService.Instance.Debug("新客户端接入");
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
ListenerList.Add(state);
Recieve(state);
}
public void StopService()
{
//Mesnac.Log.LogService.Instance.Debug("服务关闭");
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
public void RestartService()
{
StopService();
//StartService();
}
public void Send(Socket handler, String data)
{
try
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, SendAfter, handler);
}
catch (Exception e)
{
// Mesnac.Log.LogService.Instance.Debug("发送错误:" + e.ToString());
}
}
public void Recieve(StateObject state)
{
try
{
Socket handler = state.workSocket;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, RecieveAfter, state);
}
catch(Exception e)
{
// Mesnac.Log.LogService.Instance.Debug("接收错误:" + e.ToString());
}
}
//public event AsyncCallback AcceptCallback;
//public event AsyncCallback ReadCallback;
public void RecieveAfter(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
try
{
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Remove(0, state.sb.Length);
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
Console.WriteLine("Recieve Data: {0}", state.sb.ToString());
foreach (StateObject so in ListenerList)
{
if (so.workSocket == handler)
{
so.connectFlag = true;
}
}
if (ReciveEvent != null)
{
ReciveEvent(state.sb.ToString(), state);
}
}
}
catch
{
}
finally
{
Recieve(state);
}
}
public void SendAfter(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
//int bytesSent = handler.EndSend(ar);
//Console.WriteLine("Sent {0} bytes to client.", bytesSent);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//public event AsyncCallback SendCallback;
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public bool connectFlag = true;
}
}