天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

100 lines
3.1 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Sockets;
using System.Net;
using QMAPP.FJC.BLL.Operation;
namespace EQUIPINTERFACETEST
{
public class GetBarCodeTest
{
TcpListener tcpsever = null;
public event EQUIPINTERFACETEST.LeafEvent.DataReceivedHandler DataReceived;
public void StartTCPServer()
{
try
{
string serverIP = ConfigurationManager.AppSettings["ServerIP"];
string port = ConfigurationManager.AppSettings["Port"];
tcpsever = new TcpListener(IPAddress.Parse(serverIP), Convert.ToInt32(port));
tcpsever.Start();
tcpsever.BeginAcceptTcpClient(new AsyncCallback(Acceptor), tcpsever);
}
catch (Exception ex)
{
}
}
public void StopTCPServer()
{
tcpsever.Stop();
}
private string barCode = "";
private void Acceptor(IAsyncResult o)
{
TcpListener server = o.AsyncState as TcpListener;
try
{
//初始化连接的客户端
LeafTCPClient newClient = new LeafTCPClient();
newClient.NetWork = server.EndAcceptTcpClient(o);
string barcode = newClient.Name;
Console.Write(barcode);
newClient.NetWork.GetStream().BeginRead(newClient.buffer, 0, newClient.buffer.Length, new AsyncCallback(TCPCallBack), newClient);
server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//继续监听客户端连接
}
catch (ObjectDisposedException ex)
{ //监听被关闭
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void TCPCallBack(IAsyncResult ar)
{
LeafTCPClient client = (LeafTCPClient)ar.AsyncState;
if (client.NetWork.Connected)
{
NetworkStream ns = client.NetWork.GetStream();
byte[] recdata = new byte[ns.EndRead(ar)];
barCode = new ASCIIEncoding().GetString(recdata);
if (string.IsNullOrEmpty(barCode) == false)
{
ProductBLL productbll = new ProductBLL();
productbll.InsertAirbagSupportPackage(barCode);
}
if (recdata.Length > 0)
{
Array.Copy(client.buffer, recdata, recdata.Length);
//if (DataReceived != null)
//{
// DataReceived.BeginInvoke(client.Name, recdata, null, null);//异步输出数据
//}
ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
}
else
{
client.DisConnect();
}
}
}
}
}