请教如何改善C#中socket通信机客户端程序的健壮性

我是做Socket的新手,最近做了一个Socket客户端程序,连接Server的时候,如果server存在,并且允许连接的话,程序无错,正常执行;但是如果Server不存在,或者拒绝连接,程序就会卡住,此时不提示出错。开始我以为是没有Catch异常,但是检查了程序,异常情况都Catch掉了,程序还是卡。

请各位大虾帮忙指正!谢谢,以下是我这个模块的代码!

using System;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace 测试程序
{
///

1<summary>   
2/// ClassClient 的摘要说明。   
3/// </summary>

public class ClassClient
{
//方法
public ClassClient()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

//函数

#region socket通信机连接函数
///

1<summary>   
2/// socket通信机连接函数   
3/// </summary>

///

1<param name="remoteEP"/>

远程终端
///

1<param name="client"/>

建立客户端
public byte SocketConnect(EndPoint RemoteEP, Socket Client)
{
//调用系统连接函数
Client.BeginConnect(RemoteEP,new AsyncCallback(ConnectCallback), Client );

ConnectDone.WaitOne();

return(1);

}
#endregion

#region socket连接返回函数
///

1<summary>   
2/// socket连接返回函数   
3/// </summary>

///

1<param name="ar"/>

表示异步操作的状态
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// 获取socket连接实例
Socket client = (Socket) ar.AsyncState;

// 完成连接过程.
client.EndConnect(ar);

// 置位连接完成标志
ConnectDone.Set();

// 得到连接成功信息
ConnectInfo="连接成功!";
}
catch (Exception e)
{
// 得到连接失败信息
ConnectInfo=e.ToString ();

// 结束连接
ConnectDone.Reset ();
}
}
#endregion

#region socket通信机关闭函数
///

1<summary>   
2/// socket通信机关闭函数   
3/// </summary>

///

1<param name="Client"/>

需关闭的socket通信实例
public byte SocketClose(Socket Client)
{
try
{
if (Client!=null)
{
//如果仍然产生通信信息,则禁用
if (Client.Connected)
{
Client.Shutdown(SocketShutdown.Both);
}
//关闭socket通信
Client.Close();

//获得关闭成功信息
CloseInfo = "通信机已关闭!";
}
return(1);
}
catch (Exception e)
{
//获得关闭通信失败信息
CloseInfo = e.ToString();

return(0);
}
}
#endregion

#region 数据发送函数
///

1<summary>   
2/// 数据发送函数   
3/// </summary>

///

1<param name="Client"/>

已连接的socket通信机实例(客户端)
///

1<param name="MessageSend"/>

需发送的信息
///

1<returns>   
2/// 返回发送是否成功值   
3/// </returns>

public bool SocketSend(Socket Client, String MessageSend)
{
//将数据转换成Byte型ASCII码。
byte[] ByteData = Encoding.ASCII.GetBytes(MessageSend);

// 向远程设备(Server)发送数据.
Client.BeginSend(ByteData, 0, ByteData.Length, SocketFlags.None,new AsyncCallback(SendCallback), Client);

//发送标志事件等待
SendDone.WaitOne();

//返回真
return(true);
}
#endregion

#region 数据发送返回函数
///

1<summary>   
2/// 数据发送返回函数   
3/// </summary>

///

1<param name="ar"/>

表示异步操作的状态
private static void SendCallback(IAsyncResult ar)
{
try
{
// 获取socket连接实例
Socket Client = (Socket) ar.AsyncState;

// 对远程设备发送数据完成
int bytesSent = Client.EndSend(ar);

//置位发送完成标志
SendDone.Set();

// 获得发送完成信息
SendInfo="发送已完成!";

}
catch (Exception e)
{
//得到发送失败信息
SendInfo=e.ToString();

//结束发送标志
SendDone.Reset();
}
}

#endregion

#region 数据接收函数
///

1<summary>   
2/// 数据接收函数   
3/// </summary>

///

1<param name="client"/>

已连接的socket通信机实例(客户端)
///

1<returns>   
2/// 返回接收数据   
3/// </returns>

public string SocketReceive(Socket Client)
{
try
{
int i;

// 创建实例.
StateObject State = new StateObject();
State.WorkSocket = Client;

// 开始从远程设备接收数据
Client.BeginReceive( State.Buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), State);

//将接收的byte数据转化为字符串
for (i=0;i

 1<state.buffer #endregion="" #region="" ();="" (exception="" +="State.Buffer[i].ToString" .length="" ;i++)="" <summary="" catch="" e)="" return("");="" return(revdata);="" revdata="" revinfo="e.ToString();" {="" }="" 数据接收返回函数="" 获得接收失败信息="" 返回接收到的数据="" 返回空字符串="">   
 2/// 数据接收返回函数   
 3///    
 4/// <param name="ar"/>表示异步操作的状态   
 5private static void ReceiveCallback( IAsyncResult ar )   
 6{   
 7try   
 8{   
 9// 创建实例   
10StateObject State = (StateObject) ar.AsyncState;   
11Socket Client = State.WorkSocket; 
12
13// 从远程设备读取数据   
14int BytesRead = Client.EndReceive(ar); 
15
16if (BytesRead &gt; 0)   
17{   
18// 可能有过多的数据,先存储缓冲区内的字符串   
19RevTempString = Encoding.ASCII.GetString(State.Buffer,0,BytesRead);   
20State.SB.Append(RevTempString); 
21
22// 接收剩余数据   
23Client.BeginReceive(State.Buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReceiveCallback), State);   
24}   
25else   
26{   
27// 所有数据都已经接收   
28if (State.SB.Length &gt; 1)   
29{   
30string response = State.SB.ToString();   
31} 
32
33// 置位数据已接收标志位   
34ReceiveDone.Set();   
35}   
36}   
37catch (Exception e)   
38{   
39// 获得接收失败信息   
40RevInfo=e.ToString();   
41}   
42}   
43#endregion 
44
45#region 字段   
46private static ManualResetEvent SendDone = new ManualResetEvent(false);   
47private static ManualResetEvent ConnectDone = new ManualResetEvent(false);   
48private static ManualResetEvent ReceiveDone = new ManualResetEvent(false); 
49
50public static string ConnectInfo = "";   
51public static string CloseInfo = "";   
52public static string SendInfo = "";   
53public static string RevInfo = "";   
54public static string RevData = "";   
55public static string RevTempString = ""; 
56
57  
58public class StateObject   
59{   
60// Client socket.   
61public Socket WorkSocket = null;   
62// Size of receive buffer.   
63public const int BufferSize = 2048;   
64// Receive buffer.   
65public byte[] Buffer = new byte[BufferSize];   
66// Received data string.   
67public StringBuilder SB = new StringBuilder();   
68}   
69#endregion   
70  
71}   
72}</state.buffer>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus