110,533
社区成员
发帖
与我相关
我的任务
分享
private IPEndPoint localEndPoint;
private Socket mySocket;
private bool B_receive_Frm= fase;
public Thread LstThReceive = null;
//启动接收
protected void StartTcpRec()
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
localEndPoint = new IPEndPoint(ipAddress, 5000);
mySocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
mySocket.Bind(localEndPoint);
try
{
LstThReceive = new Thread(new ThreadStart(Listerner));
LstThReceive.IsBackground = true;
B_receive_Frm = true;
LstThReceive.Start();
}
catch (Exception e)
{
throw new Exception(" Start SOCKET:" + e.Message);
}
}
/// <summary>
/// 监听数据
/// </summary>
protected void Listerner()
{
try
{
mySocket.Listen(100);
while (B_receive_Frm == true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
// Console.WriteLine("Waiting for a connection...");
mySocket.BeginAccept(
new AsyncCallback(AcceptCallback),
mySocket);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (System.ObjectDisposedException e)
{
throw new Exception("SOCKET OBJECT : " + e.Message);
}
catch (Exception ex)
{
throw new Exception(" SOCKET Listerner: " + ex.Message);
}
}
/// <summary>
/// 异步接受数据
/// </summary>
/// <param name="ar"></param>
protected void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
//下面就是异步处理的一些代码就不贴了.
}
/// 异步接受数据
/// </summary>
/// <param name="ar"></param>
protected void AcceptCallback(IAsyncResult ar)
{
mySocket.BeginAccept(
new AsyncCallback(AcceptCallback),
mySocket);
//下面就是异步处理的一些代码就不贴了.
}