socket 网络打印失败.连接不上 Socket网络 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 那你是不是没有有OnConnect函数呢? 这段代码是我从网上找的.没有找到关于OnConnect函数 class TimeOutSocket{ private static bool IsConnectionSuccessful = false; private static Exception socketexception; private static ManualResetEvent TimeoutObject = new ManualResetEvent(false); public static TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond) { TimeoutObject.Reset(); socketexception = null; string serverip = Convert.ToString(remoteEndPoint.Address); int serverport = remoteEndPoint.Port; TcpClient tcpclient = new TcpClient(); tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient); if (TimeoutObject.WaitOne(timeoutMiliSecond, false)) { if (IsConnectionSuccessful) { return tcpclient; } else { throw socketexception; } } else { tcpclient.Close(); throw new TimeoutException("TimeOut Exception"); } } private static void CallBackMethod(IAsyncResult asyncresult) { try { IsConnectionSuccessful = false; TcpClient tcpclient = asyncresult.AsyncState as TcpClient; if (tcpclient.Client != null) { tcpclient.EndConnect(asyncresult); IsConnectionSuccessful = true; } } catch (Exception ex) { IsConnectionSuccessful = false; socketexception = ex; } finally { TimeoutObject.Set(); } }} /// <summary> /// 通知事件类型 /// </summary> public enum NotifyEvents { Connected, DataSent, DataReceived, Disconnected, ConnectError, SendError, ReceiveError, DisconnectError, OtherError } /// <summary> /// 通知事件委托 /// </summary> /// <param name="notifyEvent">事件类型</param> /// <param name="eventMessage">事件消息</param> /// <param name="data">数据内容</param> public delegate void NotifyEventHandler(NotifyEvents notifyEvent, string eventMessage, object data); //socket异步通讯类 public class DeviceSocket { public Socket mySocket = null; // 处理同步 ManualResetEvent asyncEvent = new ManualResetEvent(true); public string receiveBuf = null; private const int BUFFER_SIZE = 1024; //通知事件 public event NotifyEventHandler Notify; // Closing flag private bool closing = false; byte[] bRcvd = new byte[BUFFER_SIZE]; /// <summary> ///连接到一个网络地址 /// </summary> public void Connect(String ip, int port) { mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 将事件状态设置为非终止状态,导致线程阻止 asyncEvent.Reset(); // 准备异步socket IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port); //开始异步连接主机 mySocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null); // 等待所有异步操作都完成 //asyncEvent.WaitOne(); } /// <summary> /// 确定Socket是否连接,有时Socket的Connected是true,但不能一定保证已连接 ///需通过poll已确认是否真的已连接 /// /// 连接返回true,否则false; /// </summary> public bool IsConnected { get { if (mySocket == null) return false; if (!mySocket.Connected) return false; //确保socket已连接,即使Conected属性已连接 try { // 确定socket是否连接 return !mySocket.Poll(1, SelectMode.SelectError); } catch { return false; } } } /// <summary> /// Async connect callback /// </summary> private void OnConnect(IAsyncResult ar) { try { // 接收挂起的异步连接请求 mySocket.EndConnect(ar); // 通知主线程已连接 NotifyCaller(NotifyEvents.Connected, null); } catch (Exception ex) { NotifyCaller(NotifyEvents.ConnectError, ex.Message); } } /// <summary> /// 断开已连接的socket /// </summary> public void Disconnect() { // 如果socket没有被创建,直接返回 if (mySocket == null) return; closing = true; try { mySocket.Shutdown(SocketShutdown.Both); } catch { } try { mySocket.Close(); // 等待所有异步操作直至完成 //asyncEvent.WaitOne(); } catch { } closing = false; NotifyCaller(NotifyEvents.Disconnected, "断开成功"); } /// <summary> /// 发送数据 /// </summary> public void Send(String data) { // String to byet byte[] byteArray = Encoding.Default.GetBytes(data); Send(byteArray); } public void Send(byte[] byteData) { try { //发送数据给已连接的socket mySocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); asyncEvent.Reset(); } catch (Exception ex) { NotifyCaller(NotifyEvents.SendError, ex.Message, byteData); } } /// <summary> /// 异步通知发送数据的主线程 /// </summary> private void OnSend(IAsyncResult ar) { try { int sendLen = mySocket.EndSend(ar); //通知发送成功和发送的数据长度 NotifyCaller(NotifyEvents.DataSent, sendLen.ToString()); } catch (Exception ex) { NotifyCaller(NotifyEvents.SendError, ex.Message); } } /// <summary> /// 接收数据 /// </summary> public void Receive() { try { asyncEvent.Reset(); mySocket.BeginReceive(bRcvd, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(OnReceive), null); //Thread.Sleep(1000); } catch (Exception ex) { NotifyCaller(NotifyEvents.ReceiveError, ex.Message); } } /// <summary> /// 异步回传接收到的数据 /// </summary> private void OnReceive(IAsyncResult ar) { try { int len = mySocket.EndReceive(ar); receiveBuf = ASCIIEncoding.ASCII.GetString(bRcvd, 0, len); //通知数据接收成功,并返回接收的数据给接收数据的线程 NotifyCaller(NotifyEvents.DataReceived, null, receiveBuf); } catch (Exception ex) { NotifyCaller(NotifyEvents.ReceiveError, ex.Message); } } /// <summary> /// 通知发送数据的线程 /// </summary> private void NotifyCaller(NotifyEvents nEvent, string message, object data) { asyncEvent.Set(); //当没有绑定事件和已断开连接时不发送通知 if ((this.Notify != null) && !closing) Notify(nEvent, message, data); } public void NotifyCaller(NotifyEvents nEvent, string message) { asyncEvent.Set(); //当没有绑定事件和已断开连接时不发送通知 if ((this.Notify != null) && !closing) Notify(nEvent, message, null); } }这个就是类,但是每次连接的时候socket.IsConnected;都是false,连接不上 存储过程赋值方式? C#程序重新启动的问题 .net发布网站问题 如何检验一个类一段时间内是否被触发过 WPF Canvas层次的问题 有没有MVP在啊,真的很奇怪的问题。 sarcophile(食肉动物),请到此接分! 选择word中的文本 请教高人:如何让自定义Windows窗体控件在设计期按F1时可以打开自己的帮助文件! 如何将VS 中文本框的值传递给SQL存储过程(急) c#服务器传的文件流,把它下载到本地,不是覆盖,是直接下载到文件夹下面 socket里面的BeginReceive,求指导!
{
private static bool IsConnectionSuccessful = false;
private static Exception socketexception;
private static ManualResetEvent TimeoutObject = new ManualResetEvent(false); public static TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
TimeoutObject.Reset();
socketexception = null; string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient(); tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient); if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
throw new TimeoutException("TimeOut Exception");
}
}
private static void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient; if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
}
/// 通知事件类型
/// </summary>
public enum NotifyEvents
{
Connected,
DataSent,
DataReceived,
Disconnected,
ConnectError,
SendError,
ReceiveError,
DisconnectError,
OtherError
}
/// <summary>
/// 通知事件委托
/// </summary>
/// <param name="notifyEvent">事件类型</param>
/// <param name="eventMessage">事件消息</param>
/// <param name="data">数据内容</param>
public delegate void NotifyEventHandler(NotifyEvents notifyEvent, string eventMessage, object data); //socket异步通讯类
public class DeviceSocket
{
public Socket mySocket = null; // 处理同步
ManualResetEvent asyncEvent = new ManualResetEvent(true); public string receiveBuf = null;
private const int BUFFER_SIZE = 1024; //通知事件
public event NotifyEventHandler Notify; // Closing flag
private bool closing = false;
byte[] bRcvd = new byte[BUFFER_SIZE]; /// <summary>
///连接到一个网络地址
/// </summary>
public void Connect(String ip, int port)
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 将事件状态设置为非终止状态,导致线程阻止
asyncEvent.Reset(); // 准备异步socket
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port); //开始异步连接主机
mySocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null); // 等待所有异步操作都完成
//asyncEvent.WaitOne();
} /// <summary>
/// 确定Socket是否连接,有时Socket的Connected是true,但不能一定保证已连接
///需通过poll已确认是否真的已连接
///
/// 连接返回true,否则false;
/// </summary>
public bool IsConnected
{
get
{
if (mySocket == null) return false; if (!mySocket.Connected) return false; //确保socket已连接,即使Conected属性已连接
try
{
// 确定socket是否连接
return !mySocket.Poll(1, SelectMode.SelectError);
}
catch
{
return false;
}
}
} /// <summary>
/// Async connect callback
/// </summary>
private void OnConnect(IAsyncResult ar)
{
try
{
// 接收挂起的异步连接请求
mySocket.EndConnect(ar); // 通知主线程已连接
NotifyCaller(NotifyEvents.Connected, null);
}
catch (Exception ex)
{
NotifyCaller(NotifyEvents.ConnectError, ex.Message);
}
} /// <summary>
/// 断开已连接的socket
/// </summary>
public void Disconnect()
{
// 如果socket没有被创建,直接返回
if (mySocket == null) return; closing = true; try
{
mySocket.Shutdown(SocketShutdown.Both);
}
catch { } try
{
mySocket.Close(); // 等待所有异步操作直至完成
//asyncEvent.WaitOne();
}
catch { } closing = false;
NotifyCaller(NotifyEvents.Disconnected, "断开成功");
} /// <summary>
/// 发送数据
/// </summary>
public void Send(String data)
{
// String to byet
byte[] byteArray = Encoding.Default.GetBytes(data);
Send(byteArray);
} public void Send(byte[] byteData)
{
try
{ //发送数据给已连接的socket
mySocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); asyncEvent.Reset();
}
catch (Exception ex)
{
NotifyCaller(NotifyEvents.SendError, ex.Message, byteData);
}
} /// <summary>
/// 异步通知发送数据的主线程
/// </summary>
private void OnSend(IAsyncResult ar)
{
try
{ int sendLen = mySocket.EndSend(ar); //通知发送成功和发送的数据长度
NotifyCaller(NotifyEvents.DataSent, sendLen.ToString());
}
catch (Exception ex)
{
NotifyCaller(NotifyEvents.SendError, ex.Message);
}
} /// <summary>
/// 接收数据
/// </summary>
public void Receive()
{
try
{
asyncEvent.Reset(); mySocket.BeginReceive(bRcvd, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(OnReceive), null); //Thread.Sleep(1000);
}
catch (Exception ex)
{
NotifyCaller(NotifyEvents.ReceiveError, ex.Message);
}
} /// <summary>
/// 异步回传接收到的数据
/// </summary>
private void OnReceive(IAsyncResult ar)
{
try
{
int len = mySocket.EndReceive(ar);
receiveBuf = ASCIIEncoding.ASCII.GetString(bRcvd, 0, len); //通知数据接收成功,并返回接收的数据给接收数据的线程
NotifyCaller(NotifyEvents.DataReceived, null, receiveBuf);
}
catch (Exception ex)
{
NotifyCaller(NotifyEvents.ReceiveError, ex.Message);
}
} /// <summary>
/// 通知发送数据的线程
/// </summary>
private void NotifyCaller(NotifyEvents nEvent, string message, object data)
{ asyncEvent.Set(); //当没有绑定事件和已断开连接时不发送通知
if ((this.Notify != null) && !closing)
Notify(nEvent, message, data);
}
public void NotifyCaller(NotifyEvents nEvent, string message)
{
asyncEvent.Set(); //当没有绑定事件和已断开连接时不发送通知
if ((this.Notify != null) && !closing)
Notify(nEvent, message, null);
}
}这个就是类,但是每次连接的时候socket.IsConnected;都是false,连接不上