日期:2014-05-18  浏览次数:20787 次

C# socket编程
socket中如何判断一个已连接的用户退出,并清空登陆上来的记录.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace Gps_GateWay
{
   
  public partial class Form1 : Form
  {
  public static ManualResetEvent allDone = new ManualResetEvent(false);
  private Thread th;
  private bool listenerRun = true;
  Socket listener;
  private const int maxsocket = 10;
   
  public Form1()
  {
  InitializeComponent();
  }

  private IPAddress GetLocalIP()
  {
  IPHostEntry iphostentry = Dns.GetHostByName(Dns.GetHostName());
  return iphostentry.AddressList[0];
  }

  private void Listen()
  {
  try
  {
  int port = int.Parse(txtPort.Text);
  IPAddress ipaddress = GetLocalIP();
  IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port);
  listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  listener.Bind(ipendpoint);
  listener.Listen(50);
  while (listenerRun)
  {
  allDone.Reset();
  listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);
  allDone.WaitOne();
  }
  }
  catch (Exception Err)
  {
  MessageBox.Show(Err.Message);
  }
  }

  private delegate void GetLstControl(string hostname, string remoteip, string remoteport);

  private void GetLstStr(string hostname, string remoteip, string remoteport)
  {
  lstIP.Items.Add("[" + hostname + "] " + remoteip + ":" + remoteport);
  }


  private void AcceptCallBack(IAsyncResult ar)
  {
  try
  {
  allDone.Set();
  Socket sok = (Socket)ar.AsyncState;
  Socket client = sok.EndAccept(ar);
   
  StateObject state = new StateObject();
  state.workSocket = client;


  EndPoint remoteendpoint = client.RemoteEndPoint;
  IPEndPoint ipendpoint = (IPEndPoint)remoteendpoint;
  string remoteip = ipendpoint.Address.ToString();
  string remoteport = ipendpoint.Port.ToString();

  IPHostEntry iphostentry = Dns.GetHostByAddress(ipendpoint.Address);
  string hostname = iphostentry.HostName;
  GetLstControl getlst = new GetLstControl(GetLstStr);
  this.BeginInvoke(getlst,new object[]{hostname,remoteip,remoteport});

  client.BeginReceive(state.buffer, 0,StateObject.BufferSize,0, new AsyncCallback(ReadCallBack), state);
  }
  catch (Exception Err)
  {
  // MessageBox.Show(Err.Message);
  }