首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于socket异步的有关问题

2012-01-19 
关于socket异步的问题根据MSDN上的例子改过,代码如下:SocketListener.csusing Systemusing System.Collec

关于socket异步的问题
根据MSDN上的例子改过,代码如下:

SocketListener.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace PDAserver
{
  public class StateObject
  {
  // Client socket.
  public Socket workSocket = null;
  // Size of receive buffer.
  public const int BufferSize = 1024;
  // Receive buffer.
  public byte[] buffer = new byte[BufferSize];
  // Received data string.
  public StringBuilder sb = new StringBuilder();
  }

  public class SocketListener
  {
  // Thread signal.
  public static ManualResetEvent allDone = new ManualResetEvent(false);
  public String content;

  public SocketListener()
  {
  }

  public void StartListening()
  {
  // Data buffer for incoming data.
  byte[] bytes = new Byte[1024];
  //
  IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
  IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 18600);

  // Create a TCP/IP socket.
  Socket listener = new Socket(AddressFamily.InterNetwork,
  SocketType.Stream, ProtocolType.Tcp);

  // Bind the socket to the local endpoint and listen for incoming connections.
  try
  {
  listener.Bind(localEndPoint);
  listener.Listen(100);

  while (true)
  {
  // Set the event to nonsignaled state.
  allDone.Reset();

  // Start an asynchronous socket to listen for connections.
  Console.WriteLine("Waiting for a connection...");
  listener.BeginAccept(
  new AsyncCallback(AcceptCallback),
  listener);

  // Wait until a connection is made before continuing.
  allDone.WaitOne();
  }

  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }

  Console.WriteLine("\nPress ENTER to continue...");
  Console.Read();

  }

  public void AcceptCallback(IAsyncResult ar)
  {
  // Signal the main thread to continue.
  allDone.Set();

  // Get the socket that handles the client request.
  Socket listener = (Socket)ar.AsyncState;
  Socket handler = listener.EndAccept(ar);

  // Create the state object.
  StateObject state = new StateObject();
  state.workSocket = handler;
  handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  new AsyncCallback(ReadCallback), state);
  }

  public void ReadCallback(IAsyncResult ar)
  {
  //content = String.Empty;

  // Retrieve the state object and the handler socket


  // from the asynchronous state object.
  StateObject state = (StateObject)ar.AsyncState;
  Socket handler = state.workSocket;

  //结束本次接收并返回接收到的数据长度 
  int bytesRead = handler.EndReceive(ar);

  if (bytesRead > 0)
  {
  content = System.Text.Encoding.Default.GetString(state.buffer, 0, bytesRead);
  string[] arr = content.Split('\\');
  string pdaid = arr[1];
  Send(handler, pdaid);

  //if (content.IndexOf("<EOF>") > -1)
  //{
  // // All the data has been read from the 
  // // client. Display it on the console.
  // Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  // content.Length, content);
  // //将接收到的数据返回客户端
  // Send(handler, content);
  //}
  //else
  //{
  // // Not all data received. Get more.
  // handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  // new AsyncCallback(ReadCallback), state);
  //}
  }
  }

  private void Send(Socket handler, String data)
  {
  // Convert the string data to byte data using ASCII encoding.
  byte[] byteData = Encoding.ASCII.GetBytes(data);

  // Begin sending the data to the remote device.
  handler.BeginSend(byteData, 0, byteData.Length, 0,
  new AsyncCallback(SendCallback), handler);
  }

  private void SendCallback(IAsyncResult ar)
  {
  try
  {
  // Retrieve the socket from the state object.
  Socket handler = (Socket)ar.AsyncState;

  // Complete sending the data to the remote device.
  int bytesSent = handler.EndSend(ar);
  Console.WriteLine("Sent {0} bytes to client.", bytesSent);

  handler.Shutdown(SocketShutdown.Both);
  handler.Close();

  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }
  }
}

**********************************************************************************

PdaserverForm.cs

 SocketListener tc = new SocketListener();
 myThread = new Thread(new ThreadStart(tc.StartListening));
 myThread.Start();
 rtfTake.Text = tc.content;
 btnStart.Enabled = false;



   
我在SocketListener.cs中声明了一个string content,在PdaserverForm.cs中调用它 rtfTake.Text = tc.content;
可是rtfTake文本框却怎么也取不到值,请高手指教!

[解决办法]
你的异步Socket还没返回你就把tc.Content赋给rtfTake.Text了吧

你可以在你的SocketListener里面声明一个even, 当异步Socket有东西回来, 并且赋给了Content后就Raise up, 然后在你的pdaserverForm里面接到这个事件时,再做rtfTake.Text的赋值动作
[解决办法]
if (bytesRead > 0) 

content = System.Text.Encoding.Default.GetString(state.buffer, 0, bytesRead); 

//这里你收到Message, 就在这里抛出一个even, 通知其他程序去接收Content



string[] arr = content.Split( '\\ '); 
string pdaid = arr[1]; 
Send(handler, pdaid);
}
[解决办法]
还有问题, 参考下我写的这个异步Socket吧

http://blog.csdn.net/LeoMaya/archive/2007/08/06/1728518.aspx
[解决办法]
有异常吗?
异步操作中很可能要用Form.Invoke()通过主线程来修改界面上控件的值

热点排行