程序|客户端
我是做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 测试程序
{
/// <summary>
/// ClassClient 的摘要说明。
/// </summary>
public class ClassClient
{
//方法
public ClassClient()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
//函数
#region socket通信机连接函数
/// <summary>
/// socket通信机连接函数
/// </summary>
/// <param name="remoteEP">远程终端</param>
/// <param name="client">建立客户端</param>
public byte SocketConnect(EndPoint RemoteEP, Socket Client)
{
//调用系统连接函数
Client.BeginConnect(RemoteEP,new AsyncCallback(ConnectCallback), Client );
ConnectDone.WaitOne();
return(1);
}
#endregion
#region socket连接返回函数
/// <summary>
/// socket连接返回函数
/// </summary>
/// <param name="ar">表示异步操作的状态</param>
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通信机关闭函数
/// <summary>
/// socket通信机关闭函数
/// </summary>
/// <param name="Client">需关闭的socket通信实例</param>
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 数据发送函数
/// <summary>
/// 数据发送函数
/// </summary>
/// <param name="Client">已连接的socket通信机实例(客户端)</param>
/// <param name="MessageSend">需发送的信息</param>
/// <returns>
/// 返回发送是否成功值
/// </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 数据发送返回函数
/// <summary>
/// 数据发送返回函数
/// </summary>
/// <param name="ar">表示异步操作的状态</param>
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 数据接收函数
/// <summary>
/// 数据接收函数
/// </summary>
/// <param name="client">已连接的socket通信机实例(客户端)</param>
/// <returns>
/// 返回接收数据
/// </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<State.Buffer .Length ;i++)
{
RevData += State.Buffer[i].ToString ();
}
//返回接收到的数据
return(RevData);
}
catch (Exception e)
{
//获得接收失败信息
RevInfo = e.ToString();
//返回空字符串
return("");
}
}
#endregion
#region 数据接收返回函数
/// <summary>
/// 数据接收返回函数
/// </summary>
/// <param name="ar">表示异步操作的状态</param>
private static void ReceiveCallback( IAsyncResult ar )
{
try
{
// 创建实例
StateObject State = (StateObject) ar.AsyncState;
Socket Client = State.WorkSocket;
// 从远程设备读取数据
int BytesRead = Client.EndReceive(ar);
if (BytesRead > 0)
{
// 可能有过多的数据,先存储缓冲区内的字符串
RevTempString = Encoding.ASCII.GetString(State.Buffer,0,BytesRead);
State.SB.Append(RevTempString);
// 接收剩余数据
Client.BeginReceive(State.Buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReceiveCallback), State);
}
else
{
// 所有数据都已经接收
if (State.SB.Length > 1)
{
string response = State.SB.ToString();
}
// 置位数据已接收标志位
ReceiveDone.Set();
}
}
catch (Exception e)
{
// 获得接收失败信息
RevInfo=e.ToString();
}
}
#endregion
#region 字段
private static ManualResetEvent SendDone = new ManualResetEvent(false);
private static ManualResetEvent ConnectDone = new ManualResetEvent(false);
private static ManualResetEvent ReceiveDone = new ManualResetEvent(false);
public static string ConnectInfo = "";
public static string CloseInfo = "";
public static string SendInfo = "";
public static string RevInfo = "";
public static string RevData = "";
public static string RevTempString = "";
public class StateObject
{
// Client socket.
public Socket WorkSocket = null;
// Size of receive buffer.
public const int BufferSize = 2048;
// Receive buffer.
public byte[] Buffer = new byte[BufferSize];
// Received data string.
public StringBuilder SB = new StringBuilder();
}
#endregion
}
}