C#异步c语言 sockett

关于异步socket接收问题_c#吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:103,131贴子:
关于异步socket接收问题收藏
直接用MSDN的代码吧(v=vs.110).aspxC井部分关于函数BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags, AsyncCallback, Object state)在参数size的问题上如果我并不知道对方要发来多长的一个东西于是把size设置为buffer.Length那么问题来了这样会导致继续BeginReceive的时候在读取线程中阻塞那么在假定网路状态良好的情况下把MSDN代码中EndReceive方法中的继续条件if(read & 0)改为if(read &= StateObject.BUFFER_SIZE)则确实可行那么有没有人确认过在网路状况不好的情况下会遇到数据接收不全的情况
苹果刷机越狱助手哪个好?爱思助手支持一键刷机越狱,果粉最爱助手工具。
是EndReceive才会阻塞吧另外看这句话“If you are using a connection-oriented protocol, the EndReceive method will read as much data as is available up to the number of bytes you specified in the sizeparameter of the BeginReceive method.”EndReceive返回时,至多读取了BufferSize大小的数据,而不是一定会读取这么多,所以必须要用if(read & 0)
if (read & 0) {
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so); }else {
if (so.sb.Length & 1) {
//All of the data has been read, so displays it to the console
string strC
strContent = so.sb.ToString();
Console.WriteLine(String.Format(&Read {0} byte from socket& +
&data = {1} &, strContent.Length, strContent));
s.Close(); }当read&0它就会继续BeginReceive而此时没有多的数据可读取的时候这里的Async_Send_Receive.Read_Callback就不会被调用那么也就是说下面的 else 在我这里作为服务器先接收消息的时候没法这么用因为这个else是要对方close的时候read才会为0所以必须要加上判断如果消息不够长即read &= StateObject.BUFFER_SIZE或者消息长度为0即read &= 0那么读取结束哎差点被坑了
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或C# Socket异步通信 - kingmoon - 博客园
随笔 - 49, 文章 - 0, 评论 - 143, 引用 - 0
C# Socket异步通信&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
TCPServer&
1、使用的通讯通道:socket
2、用到的基本功能:
BeginAccept
BeginReceive&
EndReceive
3、函数参数说明
&Socket listener = new Socket(AddressFamily.InterNetwork,
&&&&&&&&&&& SocketType.Stream, ProtocolType.Tcp);
&新建socket所使用的参数均为系统预定义的量,直接选取使用。
listener.Bind(localEndPoint);
localEndPoint 表示一个定义完整的终端,包括IP和端口信息。
//new IPEndPoint(IPAddress,port)
//IPAdress.Parse("192.168.1.3")
listener.Listen(100);
&&& listener.BeginAccept(
&&&&&&&&&&&&&&&&&&& new AsyncCallback(AcceptCallback),
&&&&&&&&&&&&&&&&&&& listener);
& AsyncCallback(AcceptCallback),一旦连接上后的回调函数为AcceptCallback。当系统调用这个函数时,自动赋予的输入参数为IAsyncResoult类型变量ar。
&& listener,连接行为的容器。
Socket handler = listener.EndAccept(ar);
完成连接,返回此时的socket通道。
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
&&&&&&&&&&& new AsyncCallback(ReadCallback), state);
接收的字节,0,字节长度,0,接收时调用的回调函数,接收行为的容器。
容器的结构类型为:
public class StateObject{
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();}
容器至少为一个socket类型。
===============
& // Read data from the client socket.
&&&&&&& int bytesRead = handler.EndReceive(ar);
完成一次连接。数据存储在state.buffer里,bytesRead为读取的长度。
handler.BeginSend(byteData, 0, byteData.Length, 0,
&&&&&&&&&&& new AsyncCallback(SendCallback), handler);
发送数据byteData,回调函数SendCallback。容器handler
int bytesSent = handler.EndSend(ar);
发送完毕,bytesSent发送字节数。
4 程序结构
byte[] bytes = new Byte[1024];
IPAddress ipAddress = IPAddress.Parse("192.168.1.104");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// 生成一个TCP的socket
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
// Set the event to nonsignaled state.
allDone.Reset();
//开启异步监听socket
Console.WriteLine("Waiting for a connection");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// 让程序等待,直到连接任务完成。在AcceptCallback里的适当位置放置allDone.Set()语句.
allDone.WaitOne();
Console.WriteLine("\nPress ENTER to continue");
Console.Read();
&连接行为回调函数AcceptCallback:
&&& public static void AcceptCallback(IAsyncResult ar)
&&&&&&& //添加此命令,让主线程继续.
&&&&&&& allDone.Set();
&&&&&&& // 获取客户请求的socket
&&&&&&& Socket listener = (Socket)ar.AsyncS
&&&&&&& Socket handler = listener.EndAccept(ar);
&&&&&&& // 造一个容器,并用于接收命令.
&&&&&&& StateObject state = new StateObject();
&&&&&&& state.workSocket =
&&&&&&& handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
&&&&&&&&&&& new AsyncCallback(ReadCallback), state);
读取行为的回调函数ReadCallback:
&&& public static void ReadCallback(IAsyncResult ar)
&&&&&&& String content = String.E
&&&&&&& // 从异步state对象中获取state和socket对象.
&&&&&&& StateObject state = (StateObject)ar.AsyncS
&&&&&&& Socket handler = state.workS
&&&&&&& // 从客户socket读取数据.
&&&&&&& int bytesRead = handler.EndReceive(ar);
&&&&&&& if (bytesRead & 0)
&&&&&&&&&&& // 如果接收到数据,则存起来
&&&&&&&&&&& state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
&&&&&&&&&&& // 检查是否有结束标记,如果没有则继续读取
&&&&&&&&&&& content = state.sb.ToString();
&&&&&&&&&&& if (content.IndexOf("&EOF&") & -1)
&&&&&&&&&&& {
&&&&&&&&&&&&&&& //所有数据读取完毕.
&&&&&&&&&&&&&&& Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
&&&&&&&&&&&&&&&&&&& content.Length, content);
&&&&&&&&&&&&&&& // 给客户端响应.
&&&&&&&&&&&&&&& Send(handler, content);
&&&&&&&&&&& }
&&&&&&&&&&& else
&&&&&&&&&&& {
&&&&&&&&&&&&&&& // 接收未完成,继续接收.
&&&&&&&&&&&&&&& handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
&&&&&&&&&&&&&&& new AsyncCallback(ReadCallback), state);
&&&&&&&&&&& }
发送消息给客户端:
private static void Send(Socket handler, String data)
&&&&&&& // 消息格式转换.
&&&&&&& byte[] byteData = Encoding.ASCII.GetBytes(data);
&&&&&&& // 开始发送数据给远程目标.
&&&&&&& handler.BeginSend(byteData, 0, byteData.Length, 0,
&&&&&&&&&&& new AsyncCallback(SendCallback), handler);
private static void SendCallback(IAsyncResult ar)
&&&&&&&&&&& // 从state对象获取socket.
&&&&&&&&&&& Socket handler = (Socket)ar.AsyncS
&& &&&&&&&&&//完成数据发送
&&&&&&&&&&& int bytesSent = handler.EndSend(ar);
&&&&&&&&&&& Console.WriteLine("Sent {0} bytes to client.", bytesSent);
&&&&&&&&&&& handler.Shutdown(SocketShutdown.Both);
&&&&&&&&&&& handler.Close();
在各种行为的回调函数中,所对应的socket都从输入参数的AsyncState属性获得。使用(Socket)或者(StateObject)进行强制转换。BeginReceive函数使用的容器为state,因为它需要存放传送的数据。
而其余接收或发送函数的容器为socket也可。
2 &using System.N
3 &using System.Net.S
4 using System.T
5 using System.T
7 // State object for reading client data asynchronously
8 public class StateObject
socket. 11
public Socket workSocket = null; 12
// Size of receive buffer. 13
public const int BufferSize = 1024; 14
// Receive buffer. 15
public byte[] buffer = new byte[BufferSize]; 16
// Received data string. 17
public StringBuilder sb = new StringBuilder(); 18 } 19
20 public class AsynchronousSocketListener 21 { 22
// Thread signal. 23
public static ManualResetEvent allDone = new ManualResetEvent(false); 24
public AsynchronousSocketListener() 26
public static void StartListening() 30
// Data buffer for incoming data. 32
byte[] bytes = new Byte[1024]; 33
// Establish the local endpoint for the socket. 35
// The DNS name of the computer 36
// running the listener is "". 37
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 38
IPAddress ipAddress = IPAddress.Parse("192.168.1.104"); 39
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 41
// Create a TCP/IP socket. 43
Socket listener = new Socket(AddressFamily.InterNetwork, 44
SocketType.Stream, ProtocolType.Tcp); 45
// Bind the socket to the local endpoint and listen for incoming connections. 47
listener.Bind(localEndPoint); 50
listener.Listen(100); 51
while (true) 52
// Set the event to nonsignaled state. 54
allDone.Reset(); 55
// Start an asynchronous socket to listen for connections. 57
Console.WriteLine("Waiting for a connection"); 58
listener.BeginAccept( 59
new AsyncCallback(AcceptCallback), 60
listener); 61
// Wait until a connection is made before continuing. 63
allDone.WaitOne(); 64
catch (Exception e) 67
Console.WriteLine(e.ToString()); 69
Console.WriteLine("\nPress ENTER to continue"); 72
Console.Read(); 73
public static void AcceptCallback(IAsyncResult ar) 76
// Signal the main thread to continue. 78
allDone.Set(); 79
// Get the socket that handles the client request. 81
Socket listener = (Socket)ar.AsyncS 82
Socket handler = listener.EndAccept(ar); 83
// Create the state object. 85
StateObject state = new StateObject(); 86
state.workSocket = 87
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); 88
public static void ReadCallback(IAsyncResult ar) 91
String content = String.E 93
// Retrieve the state object and the handler socket 95
// from the asynchronous state object. 96
StateObject state = (StateObject)ar.AsyncS 97
Socket handler = state.workS 98
// Read data from the client socket. 100
int bytesRead = handler.EndReceive(ar);101 102
if (bytesRead & 0)103
might be more data, so store the data received so far.105
state.sb.Append(Encoding.ASCII.GetString(106
state.buffer, 0, bytesRead));107 108
// Check for end-of-file tag. If it is not there, read 109
// more data.110
content = state.sb.ToString();111
if (content.IndexOf("&EOF&") & -1)112
// All the data has been read from the 114
// client. Display it on the console.115
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);116 117
// Echo the data back to the client.118
Send(handler, content);119
// Not all data received. Get more.123
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);124
private static void Send(Socket handler, String data)129
// Convert the string data to byte data using ASCII encoding.131
byte[] byteData = Encoding.ASCII.GetBytes(data);132 133
// Begin sending the data to the remote device.134
handler.BeginSend(byteData, 0, byteData.Length, 0,135
new AsyncCallback(SendCallback), handler);136
private static void SendCallback(IAsyncResult ar)141 142
// Retrieve the socket from the state object.146
Socket handler = (Socket)ar.AsyncS147 148
// Complete sending the data to the remote device.149
int bytesSent = handler.EndSend(ar);150
Console.WriteLine("Sent {0} bytes to client.", bytesSent);151
handler.Shutdown(SocketShutdown.Both);152
handler.Close();153
catch (Exception e)156 157
Console.WriteLine(e.ToString());159
public static int Main(String[] args)163 164
StartListening();166
return 0;167
}168 169 }2015年3月 总版技术专家分月排行榜第二2014年12月 总版技术专家分月排行榜第二2014年9月 总版技术专家分月排行榜第二
2015年3月 .NET技术大版内专家分月排行榜第一2015年2月 .NET技术大版内专家分月排行榜第一2015年1月 .NET技术大版内专家分月排行榜第一2014年12月 .NET技术大版内专家分月排行榜第一2014年11月 .NET技术大版内专家分月排行榜第一
2015年3月 总版技术专家分月排行榜第二2014年12月 总版技术专家分月排行榜第二2014年9月 总版技术专家分月排行榜第二
2015年3月 .NET技术大版内专家分月排行榜第一2015年2月 .NET技术大版内专家分月排行榜第一2015年1月 .NET技术大版内专家分月排行榜第一2014年12月 .NET技术大版内专家分月排行榜第一2014年11月 .NET技术大版内专家分月排行榜第一
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。}

我要回帖

更多关于 c语言 socket 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信