读书人

C# socket编程解决办法

发布时间: 2011-12-29 22:09:38 作者: rapoo

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);
}
}

private delegate void GetRchControl(string str);


private void GetRchMsg(string str)
{
rchMsg.AppendText(str);
}

private void ReadCallBack(IAsyncResult ar)
{
try
{

StateObject state = (StateObject)ar.AsyncState;
Socket hander = state.workSocket;


int readbyte = hander.EndReceive(ar);
if (readbyte > 0)
{
string strcontent = "";
string str_msg = "";
string strmsg = "";
strmsg=Encoding.BigEndianUnicode.GetString(state.buffer, 0, readbyte);
state.sb.Length = 0;
state.sb.Append(strmsg);
strcontent = state.sb.ToString() + "\n";

EndPoint remoteendpoint = hander.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;

string time = DateTime.Now.ToString();

str_msg = "(" + time + ") " + hostname + ":" + strcontent + "\n";

GetRchControl getrch = new GetRchControl(GetRchMsg);
this.BeginInvoke(getrch, new object[] { str_msg });

//if (strcontent.IndexOf("1") > -1)
//{
// // Send(hander, "发送成功\n");
// byte[] byteData = Encoding.BigEndianUnicode.GetBytes("发送成功\n");
// hander.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), hander);
// hander.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
//}
//else
//{
// hander.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
//}
byte[] byteData = Encoding.BigEndianUnicode.GetBytes("(" + time + ") " + "信息发送成功\n");
hander.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), hander);
hander.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);

}

}
catch (Exception Err)
{
MessageBox.Show(Err.Message);
}
}

private void Send(Socket handler, String data)
{
byte[] byteData = Encoding.BigEndianUnicode.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}

private void SendCallback(IAsyncResult ar)
{

try
{

//Socket handler = (Socket)ar.AsyncState;


//int bytesSent = handler.EndSend(ar);

//handler.Shutdown(SocketShutdown.Both);

//handler.Close();

}
catch (Exception Err)
{
MessageBox.Show(Err.Message);
}
}

private void button1_Click(object sender, EventArgs e)
{
th = new Thread(new ThreadStart(Listen));
th.Start();

}
}

public class StateObject
{

public Socket workSocket = null;

public const int BufferSize = 1024;

public byte[] buffer = new byte[BufferSize];

public StringBuilder sb = new StringBuilder();

}
}

[解决办法]
那你就在client端的程序里作处理。告诉服务器端。
[解决办法]
心跳数据
[解决办法]
ReadCallBack里面不是有try{}catch (Exception Err){} 吗?
你改成

。。。
StateObject state = (StateObject)ar.AsyncState;
Socket hander = state.workSocket;

try{}
catch (System.Net.Sockets.SocketException e)
{
。。。
// 客户端连接断开(即hander对象),这里出现异常,你捕捉并处理就是了。
}
catch (Exception Err){}

读书人网 >C#

热点推荐