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.

123 lines
3.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace SocketProcess
{
public class SocketBusness
{
public delegate void delRecive(string barcode, object o);
public delRecive ReciveEvent;
public SocketBusness()
{
SocketServer.Instance.AcceptCallback += NewClient;
SocketServer.Instance.ReadCallback += RecieveAfter;
SocketServer.Instance.SendCallback += SendAfter;
}
public void Start()
{
SocketServer.Instance.StartService(8000);
}
public void Send(StateObject state, string msg)
{
SocketServer.Instance.Send(state.workSocket,msg);
}
public void BeginRecieve(StateObject state)
{
SocketServer.Instance.Recieve(state);
}
public void NewClient(IAsyncResult ar)
{
// Signal the main thread to continue.
SocketServer.Instance.allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
SocketServer.Instance.ListenerList.Add(state);
BeginRecieve(state);
Console.WriteLine("One Client Connection : ");
}
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 SocketServer.Instance.ListenerList)
{
if (so.workSocket == handler)
{
so.connectFlag = true;
}
}
if (ReciveEvent != null)
{
ReciveEvent(state.sb.ToString(), state);
}
}
}
catch
{
}
finally
{
BeginRecieve(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 void HeartBeat()
{
foreach (StateObject so in SocketServer.Instance.ListenerList)
{
Send(so, "heartBeat");
so.connectFlag = false;
BeginRecieve(so);
}
}
}
}