c# Socket服务器端怎么来判断客户端出现断开问题,并刷新列表呢?急,在线等!!!

beanren2009 2009-10-27 12:20:06
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO ;
using System.Runtime.InteropServices;



namespace ChatServer
{
public class ClientSeverForm : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

private System.Windows.Forms.GroupBox grpSocket;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbSocketPort;
private System.Windows.Forms.TextBox tbSocketClientsNum;
private System.Windows.Forms.RichTextBox rtbSocketMsg;
private System.Windows.Forms.Button btnSocketStart;
private System.Windows.Forms.Button btnSocketStop;
private System.Windows.Forms.ListBox lbSocketClients;

//clients数组保存当前在线用户的Client对象
internal static Hashtable clients=new Hashtable();

//该服务器默认的监听的端口号
private TcpListener listener;

//服务器可以支持的最多的客户端的连接数
static int MAX_NUM=100;
private TextBox txtLogin;

//开始服务的标志
internal static bool SocketServiceFlag = false;
/// <summary>
/// 有新消息来时闪烁任务栏并且保持聊天记录内容滚动到最底端,QQ就是这么玩滴~
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[DllImport("user32.dll")]
public static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
private void rtbSocketMsg_TextChanged(object sender, EventArgs e)
{
rtbSocketMsg.ScrollToCaret();
if (this.WindowState == FormWindowState.Minimized)
{
FlashWindow(this.Handle, true);
}
}
public ClientSeverForm()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}


}


...全文
3757 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
TinySun 2011-09-20
  • 打赏
  • 举报
回复
有点儿晕,继续跟着看~
Junwillday 2011-08-22
  • 打赏
  • 举报
回复
每隔一段时间向对方发送消息,并设置sendtimeout为定值,如果在指定时间内数据包未发送完就会产生异常,如果产生异常,就可以认为对方下线了
寒勿语 2011-08-04
  • 打赏
  • 举报
回复
跟踪学习
xinyuetonghua 2010-11-06
  • 打赏
  • 举报
回复
jiaodian
beanren2009 2009-11-05
  • 打赏
  • 举报
回复
我现在有点乱,可以具体点不。正在线等
hhc123 2009-11-05
  • 打赏
  • 举报
回复
是客户端向服务器报到,不要写成服务器向户端报到
本人觉得8楼是你增加服务器负载
hhc123 2009-11-05
  • 打赏
  • 举报
回复
客户端每隔一段时间要向服务器报到,当超过一个的时间,就按客户端与服务器已断处理
beanren2009 2009-11-05
  • 打赏
  • 举报
回复
up up up up up up
xu_2007 2009-10-28
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 jiezi316 的回复:]
C# codeint read=0;try
{
read= asyn.AsynCsharpSocket.socket.EndReceive(ar);
}catch
{
read=0;
}if (read==0)
{
¡­
[/Quote]

楼主好像用的是同步吧,你给他异步的代码有毛用?
qldsrx 2009-10-28
  • 打赏
  • 举报
回复
我也觉得代码太长,就一个小小的问题,贴那么多代码,难道想让我帮你改写代码啊——不可能,20分要用那么多工作量来换不值得,而且平均分配到每人估计就1~2分了。

我就给你一个建议,那就是定时发送确认包过去,因为发送时如果出现异常,就可以知道是否断开了连接了。
xu_2007 2009-10-28
  • 打赏
  • 举报
回复
楼主朋友,代码太长,就不看了,现在告诉你一种方法:

首先,你得有一个存放SOCKET套接字的集合休,比如LIST;也就是说把每次服务器端接受连接以后返回的套接字存放在这个列表里面;定义一个方法循环检测这个列表(LIST),检测的方法为用列表里面的每个套接字向客户端发送一次数据,然后从异常捕获里面得知客户端是否断开:
try
{
//遍厉集合列表里面每个套接字对象,并使用其对象向各个客户端发送消息(代码)
}
catch(SocketException exp)
{
if(exp.ErrorCode==10052)//10052表示客户端已经断开连接,我印象中应该是10052,如果不是可以去MSDN上查下,
//清除集合列表里面的相应套接字(代码)
}

还有一点需要注意,如果用的是不同步的集合对象,比如LIST,那如果在循环中要改变它里面的元数的话需对其锁定后再修改,比如:lock(list),要不然会出错!
beanren2009 2009-10-28
  • 打赏
  • 举报
回复
6楼的不详呀,AR,,ASYN还有方法都是什么,不好学习,可以发全点不
beanren2009 2009-10-27
  • 打赏
  • 举报
回复
//在新的线程中的操作,它主要用于当接收到一个客户端请求时,确认与客户端的连接,
//并且立刻启动一个新的线程来处理和该客户端的信息交互。
private void StartSocketListen()
{
while(ClientSeverForm.SocketServiceFlag)
{
try
{
//当接收到一个客户端请求时,确认与客户端的连接
if (listener.Pending())
{
Socket socket=listener.AcceptSocket();
if(clients.Count>=MAX_NUM)
{
this.rtbSocketMsg.AppendText("已经达到了最大连接数:" +
MAX_NUM + ",拒绝新的连接\n");
socket.Close();
}
else
{
//启动一个新的线程,
//执行方法this.ServiceClient,处理用户相应的请求
Client client = new Client(this, socket);
Thread clientService=new Thread(
new ThreadStart(client.ServiceClient));
clientService.Start();
}
}
Thread.Sleep(200);
}
catch(Exception ex)
{
this.rtbSocketMsg.AppendText(ex.Message.ToString()+ "\n");
}
}
}

private void tbSocketPort_TextChanged(object sender, System.EventArgs e)
{
this.btnSocketStart.Enabled = (this.tbSocketPort.Text != "");
}


private void btnSocketStop_Click(object sender, System.EventArgs e)
{
ClientSeverForm.SocketServiceFlag = false;
this.btnSocketStart.Enabled = true;
this.btnSocketStop.Enabled = false;
}

public void addUser(string username)
{
this.rtbSocketMsg.AppendText(username + " 已经加入\n");
//将刚连接的用户名加入到当前在线用户列表中
this.lbSocketClients.Items.Add(username);
this.tbSocketClientsNum.Text = System.Convert.ToString(clients.Count);
}

public void removeUser(string username)
{
this.rtbSocketMsg.AppendText(username + " 已经离开\n");
//将刚连接的用户名加入到当前在线用户列表中
this.lbSocketClients.Items.Remove(username);
this.tbSocketClientsNum.Text = System.Convert.ToString(clients.Count);
}

public string GetUserList()
{
string Rtn="";
for(int i=0;i<lbSocketClients.Items.Count;i++)
{
Rtn=Rtn+lbSocketClients.Items[i].ToString() + "|";
}
return Rtn;
}

public void updateUI(string msg)
{
this.rtbSocketMsg.AppendText(msg + "\n");
}

private void ClientSeverForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
ClientSeverForm.SocketServiceFlag = false;
}

private void tbSocketClientsNum_TextChanged(object sender, EventArgs e)
{

}

private void grpSocket_Enter(object sender, EventArgs e)
{

}



private void lbSocketClients_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void txtLogin_TextChanged(object sender, EventArgs e)
{

}
public class Client
{
private string name;
private Socket currentSocket = null;
private string ipAddress;
private ClientSeverForm server;

//保留当前连接的状态:
//closed --> connected --> closed
private string state = "closed";

public Client(ClientSeverForm server, Socket clientSocket)
{
this.server = server;
this.currentSocket = clientSocket;
ipAddress = getRemoteIPAddress();
}

public string Name
{
get
{
return name;
}
set
{
name=value;
}
}
public Socket CurrentSocket
{
get
{
return currentSocket;
}
set
{
currentSocket=value;
}
}

public string IpAddress
{
get
{
return ipAddress;
}
}

private string getRemoteIPAddress()
{
return ((IPEndPoint)currentSocket.RemoteEndPoint).
Address.ToString();
}

//ServiceClient方法用于和客户端进行数据通信,包括接收客户端的请求,
//根据不同的请求命令,执行相应的操作,并将处理结果返回到客户端
public void ServiceClient()
{
string[] tokens=null;
byte[] buff=new byte[1024];
bool keepConnect=true;



//int keepAlive = -1744830460; // SIO_KEEPALIVE_VALS
//byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 }; //True, 20 秒, 2 秒
//tokens.IOControl(keepAlive, inValue, null);

//用循环来不断地与客户端进行交互,直到客户端发出“EXIT”命令,
//将keepConnect置为false,退出循环,关闭连接,并中止当前线程
while(keepConnect && ClientSeverForm.SocketServiceFlag)
{
tokens = null;
try
{
if (currentSocket == null ||
currentSocket.Available < 1)
{
Thread.Sleep(300);
continue;
}

//接收数据并存入buff数组中
int len = currentSocket.Receive(buff);
//将字符数组转化为字符串
string clientCommand=System.Text.Encoding.Default.GetString(
buff, 0, len);

//tokens[0]中保存了命令标志符(CONN、CHAT、PRIV、LIST或EXIT)
tokens=clientCommand.Split(new Char[]{'|'});

if (tokens == null)
{
Thread.Sleep(200);
continue;
}
}
catch(Exception e)
{
server.updateUI("发生异常:"+ e.ToString());
}

if(tokens[0]=="CONN")
{
//此时接收到的命令格式为:
//命令标志符(CONN)|发送者的用户名|,
//tokens[1]中保存了发送者的用户名
this.name = tokens[1];
if (ClientSeverForm.clients.Contains(this.name))
{
SendToClient(this, "ERR|User " + this.name + " 已经存在");

}
else
{
Hashtable syncClients = Hashtable.Synchronized(
ClientSeverForm.clients);
syncClients.Add(this.name,this);

//更新界面
server.addUser(this.name);


//对每一个当前在线的用户发送JOIN消息命令和LIST消息命令,
//以此来更新客户端的当前在线用户列表
System.Collections.IEnumerator myEnumerator =
ClientSeverForm.clients.Values.GetEnumerator();
while (myEnumerator.MoveNext())
{
Client client = (Client)myEnumerator.Current;
SendToClient(client, "JOIN|"+tokens[1]+"|");
Thread.Sleep(100);
}
//更新状态
state = "connected";
SendToClient(this, "ok");

//向客户端发送LIST命令,以此更新客户端的当前在线用户列表
string msgUsers="LIST|"+server.GetUserList();
SendToClient(this, msgUsers);
}

}
else if(tokens[0]=="LIST")
{
if (state == "connnected")
{
//向客户端发送LIST命令,以此更新客户端的当前在线用户列表
string msgUsers="LIST|"+server.GetUserList();
SendToClient(this, msgUsers);
}
else
{
//send err to server
SendToClient(this, "ERR|state error,Please login first");
}
}
else if(tokens[0]=="CHAT")
{
if (state == "connected")
{
//此时接收到的命令的格式为:
//命令标志符(CHAT)|发送者的用户名:发送内容|
//向所有当前在线的用户转发此信息
System.Collections.IEnumerator myEnumerator =
ClientSeverForm.clients.Values.GetEnumerator();
while (myEnumerator.MoveNext())
{
Client client = (Client)myEnumerator.Current;
//将“发送者的用户名:发送内容”转发给用户
SendToClient(client, tokens[1]);
}
server.updateUI(tokens[1]);
}
else
{
//send err to server
SendToClient(this, "ERR|state error,Please login first");
}
}
else if(tokens[0]=="PRIV")
{
if (state == "connected")
{
//此时接收到的命令格式为:
//命令标志符(PRIV)|发送者用户名|接收者用户名|发送内容|
//tokens[1]中保存了发送者的用户名
string sender=tokens[1];
//tokens[2]中保存了接收者的用户名
string receiver=tokens[2];
//tokens[3]中保存了发送的内容
string content=tokens[3];
string message=sender+" ---> "+receiver+": " + content;

//仅将信息转发给发送者和接收者
if (ClientSeverForm.clients.Contains(sender))
{
SendToClient(
(Client)ClientSeverForm.clients[sender], message);
}
if (ClientSeverForm.clients.Contains(receiver))
{
SendToClient(
(Client)ClientSeverForm.clients[receiver], message);
}
server.updateUI(message);
}
else
{
//send err to server
SendToClient(this, "ERR|state error,Please login first");
}
}
else if(tokens[0]=="EXIT")
{
//此时接收到的命令的格式为:命令标志符(EXIT)|发送者的用户名
//向所有当前在线的用户发送该用户已离开的信息
if (ClientSeverForm.clients.Contains(tokens[1]))
{
Client client = (Client)ClientSeverForm.clients[tokens[1]];

//将该用户对应的Client对象从clients中删除
Hashtable syncClients = Hashtable.Synchronized(
ClientSeverForm.clients);
syncClients.Remove(client.name);
server.removeUser(client.name);

//向客户端发送QUIT命令
string message="QUIT|" + tokens[1];

System.Collections.IEnumerator myEnumerator =
ClientSeverForm.clients.Values.GetEnumerator();
while (myEnumerator.MoveNext())
{
Client c = (Client)myEnumerator.Current;
SendToClient(c, message);
}
server.updateUI("QUIT");
}

//退出当前线程
break;
}
Thread.Sleep(200);
}
}

//SendToClient()方法实现了向客户端发送命令请求的功能
private void SendToClient(Client client, string msg)
{
System.Byte[] message=System.Text.Encoding.Default.GetBytes(
msg.ToCharArray());
client.CurrentSocket.Send(message,message.Length,0);
}
beanren2009 2009-10-27
  • 打赏
  • 举报
回复
private string getIPAddress()
{
// 获得本机局域网IP地址
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length<1)
{
return "";
}

return AddressList[0].ToString();
}

private static string getDynamicIPAddress( )
{
// 获得拨号动态分配IP地址
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length<2)
{
return "";
}

return AddressList[1].ToString();
}

private int getValidPort(string port)
{
int lport;

//测试端口号是否有效
try
{
//是否为空
if (port=="")
{
throw new ArgumentException(
"端口号为空,不能启动服务器");
}
lport = System.Convert.ToInt32(port);
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("无效的端口号:" + e.ToString());
this.rtbSocketMsg.AppendText("无效的端口号:" + e.ToString()+"\n");
return -1;
}
return lport;
}

public static void AcceptThread()
{
Thread.CurrentThread.IsBackground = true;
while (true)
{
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
try
{
// Accept(inOptionValues);
}
catch { }
}
}

//private static void Accept(byte[] inOptionValues)
//{
// Socket socket = Public.s_socketHandler.Accept();
// socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
// UserInfo info = new UserInfo();
// info.socket = socket;
// int id = GetUserId();
// info.Index = id;
// Public.s_userList.Add(id, info);
// socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info);
//}

//当单击“Socket启动”按钮时,便开始监听指定的Socket端口
private void btnSocketStart_Click(object sender, System.EventArgs e)
{
int port = getValidPort(tbSocketPort.Text);
if (port<0)
{
return;
}

string ip = this.getIPAddress();
try
{
IPAddress ipAdd=IPAddress.Parse(ip);
//创建服务器套接字
listener=new TcpListener(ipAdd, port);
//开始监听服务器端口
listener.Start();
this.rtbSocketMsg.AppendText("Socket服务器已经启动,正在监听" +
ip + " 端口号:" + this.tbSocketPort.Text + "\n");

//启动一个新的线程,执行方法this.StartSocketListen,
//以便在一个独立的进程中执行确认与客户端Socket连接的操作
ClientSeverForm.SocketServiceFlag = true;
Thread thread=new Thread(new ThreadStart(this.StartSocketListen));
thread.Start();
this.btnSocketStart.Enabled = false;
this.btnSocketStop.Enabled = true;
//byte[] inOptionValues = new byte[4 * 3];
//BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
//BitConverter.GetBytes((uint)15000).CopyTo(inOptionValues, 4);
//BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, 8);
//Client.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
catch(Exception ex)
{
this.rtbSocketMsg.AppendText(ex.Message.ToString()+"\n");
}


//while (bools)
//{
// try
// {

// if (newSocket[i2].Poll(-1, SelectMode.SelectRead))
// {
// if (newSocket[i2].Available > 0)
// {
// byteMessage = new byte[100];
// newSocket[i2].Receive(byteMessage, SocketFlags.None);
// string msg = System.Text.Encoding.Unicode.GetString(byteMessage);
// send(msg);
// }
// else
// {
// newSocket[i2].Shutdown(SocketShutdown.Both);
// newSocket[i2].Close();
// th1[i2].Abort();
// return;
// }
// }
// }
// catch
// {
// Thread.Sleep(10);
// continue;
// }

//}
}

beanren2009 2009-10-27
  • 打赏
  • 举报
回复
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ClientSeverForm));
this.grpSocket = new System.Windows.Forms.GroupBox();
this.lbSocketClients = new System.Windows.Forms.ListBox();
this.btnSocketStop = new System.Windows.Forms.Button();
this.rtbSocketMsg = new System.Windows.Forms.RichTextBox();
this.btnSocketStart = new System.Windows.Forms.Button();
this.tbSocketPort = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.tbSocketClientsNum = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtLogin = new System.Windows.Forms.TextBox();
this.grpSocket.SuspendLayout();
this.SuspendLayout();
//
// grpSocket
//
this.grpSocket.Controls.Add(this.txtLogin);
this.grpSocket.Controls.Add(this.lbSocketClients);
this.grpSocket.Controls.Add(this.btnSocketStop);
this.grpSocket.Controls.Add(this.rtbSocketMsg);
this.grpSocket.Controls.Add(this.btnSocketStart);
this.grpSocket.Controls.Add(this.tbSocketPort);
this.grpSocket.Controls.Add(this.label1);
this.grpSocket.Controls.Add(this.tbSocketClientsNum);
this.grpSocket.Controls.Add(this.label3);
this.grpSocket.Location = new System.Drawing.Point(19, 17);
this.grpSocket.Name = "grpSocket";
this.grpSocket.Size = new System.Drawing.Size(655, 397);
this.grpSocket.TabIndex = 13;
this.grpSocket.TabStop = false;
this.grpSocket.Text = "Socket连接监听";
this.grpSocket.Enter += new System.EventHandler(this.grpSocket_Enter);
//
// lbSocketClients
//
this.lbSocketClients.ItemHeight = 12;
this.lbSocketClients.Location = new System.Drawing.Point(10, 69);
this.lbSocketClients.Name = "lbSocketClients";
this.lbSocketClients.ScrollAlwaysVisible = true;
this.lbSocketClients.Size = new System.Drawing.Size(142, 292);
this.lbSocketClients.TabIndex = 21;
this.lbSocketClients.SelectedIndexChanged += new System.EventHandler(this.lbSocketClients_SelectedIndexChanged);
//
// btnSocketStop
//
this.btnSocketStop.Enabled = false;
this.btnSocketStop.Location = new System.Drawing.Point(542, 27);
this.btnSocketStop.Name = "btnSocketStop";
this.btnSocketStop.Size = new System.Drawing.Size(105, 26);
this.btnSocketStop.TabIndex = 20;
this.btnSocketStop.Text = "Socket停止";
this.btnSocketStop.Click += new System.EventHandler(this.btnSocketStop_Click);
//
// rtbSocketMsg
//
this.rtbSocketMsg.Location = new System.Drawing.Point(232, 66);
this.rtbSocketMsg.Name = "rtbSocketMsg";
this.rtbSocketMsg.Size = new System.Drawing.Size(415, 295);
this.rtbSocketMsg.TabIndex = 19;
this.rtbSocketMsg.Text = "";
this.rtbSocketMsg.TextChanged += new System.EventHandler(this.rtbSocketMsg_TextChanged);
//
// btnSocketStart
//
this.btnSocketStart.Location = new System.Drawing.Point(429, 27);
this.btnSocketStart.Name = "btnSocketStart";
this.btnSocketStart.Size = new System.Drawing.Size(105, 26);
this.btnSocketStart.TabIndex = 18;
this.btnSocketStart.Text = "Socket启动";
this.btnSocketStart.Click += new System.EventHandler(this.btnSocketStart_Click);
//
// tbSocketPort
//
this.tbSocketPort.Location = new System.Drawing.Point(324, 27);
this.tbSocketPort.Name = "tbSocketPort";
this.tbSocketPort.Size = new System.Drawing.Size(99, 21);
this.tbSocketPort.TabIndex = 17;
this.tbSocketPort.Text = "1234";
this.tbSocketPort.TextChanged += new System.EventHandler(this.tbSocketPort_TextChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(217, 27);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(116, 23);
this.label1.TabIndex = 16;
this.label1.Text = "Socket端口号:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tbSocketClientsNum
//
this.tbSocketClientsNum.Location = new System.Drawing.Point(129, 29);
this.tbSocketClientsNum.Name = "tbSocketClientsNum";
this.tbSocketClientsNum.ReadOnly = true;
this.tbSocketClientsNum.Size = new System.Drawing.Size(71, 21);
this.tbSocketClientsNum.TabIndex = 15;
this.tbSocketClientsNum.TextChanged += new System.EventHandler(this.tbSocketClientsNum_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(6, 33);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(117, 17);
this.label3.TabIndex = 13;
this.label3.Text = "当前在线用户:";
//
// txtLogin
//
this.txtLogin.Location = new System.Drawing.Point(169, 370);
this.txtLogin.Name = "txtLogin";
this.txtLogin.Size = new System.Drawing.Size(100, 21);
this.txtLogin.TabIndex = 14;
this.txtLogin.TextChanged += new System.EventHandler(this.txtLogin_TextChanged);
//
// ClientSeverForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(687, 452);
this.Controls.Add(this.grpSocket);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.Name = "ClientSeverForm";
this.Text = "聊天室服务器";
this.Closing += new System.ComponentModel.CancelEventHandler(this.ClientSeverForm_Closing);
this.grpSocket.ResumeLayout(false);
this.grpSocket.PerformLayout();
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ClientSeverForm());
}

jiezi316 2009-10-27
  • 打赏
  • 举报
回复

int read = 0;
try
{
read = asyn.AsynCsharpSocket.socket.EndReceive(ar);
}
catch
{
read = 0;
}
if (read == 0)
{
asyn.AsynCsharpSocket.Disconnected(asyn.AsynCsharpSocket, new DisconnectedEventArgs("远程主机已经断开"));
}
suners 2009-10-27
  • 打赏
  • 举报
回复
ye 也正在寻求中
javabegin 2009-10-27
  • 打赏
  • 举报
回复
2种情况:
第1个是Socket断开,那么Receive数据长度为0时,表示断开。
第2个如果是网络断开,那么要用KeepAlive。我看你上面代码有的
#region using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using SocketLibrary; #endregion namespace HkwsSDK { /// /// 在海康威视的SDK包上,再进行封装,供简单直接的调用. /// 目前可以控制硬盘录像机和解码器,需要两者密码一样. /// public class HKWS : IDisposable { #region (0)变量定义 /// /// 发现的文件信息结构 /// private readonly NetSDK.NET_DVR_FIND_DATA[] FindData = new NetSDK.NET_DVR_FIND_DATA[1000]; /// /// 远程录像状态 /// public int _StatusSaveMp4; /// /// 功能:设定播放延迟和流畅。 /// 调节播放的延时和流畅程度,如果buffNum值越大,播放的流畅性越好, /// 相应的延时比较大,buffNum值越小,播放的延时很小, /// 但是当网络不太顺畅的时候,会有丢帧现象,感觉播放不会很流畅。 /// 一般设置的帧缓冲大于等于6帧时,音频预览才会正常, /// 如果不需要音频预览,只需要视频实时性则这个值可以设置的更小。 /// public int buffNum = 10; public int bytesReturned; public int channel = 1; public int channelCount = 5; // 共8个通道 public int channelStart = 1; /// /// 客户端信息结构 /// public NetSDK.NET_DVR_CLIENTINFO ClientInfo; /// /// 解码器通道信息 /// public NetSDK.NET_DVR_MATRIX_DEC_CHAN_INFO dci; /// /// 解码器设备配置信息结构 /// public NetSDK.NET_DVR_DEVICECFG DecoderDeviceCfg; /// /// 解码器设备信息结构体结构实体化 /// public NetSDK.NET_DVR_DEVICEINFO DecoderDeviceInfo; /// /// 解码器信息结构体实例化 /// public Server_Info DecoderInfo; /// /// 解码器登录用户id /// public int decoderUserID; /// /// 硬盘录像机设备配置信息结构 /// public NetSDK.NET_DVR_DEVICECFG DvrDeviceCfg; /// /// 硬盘录像机设备信息结构体结构

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧