Socket BeginReceive 异步接收问题。代码相当短,请进来看看。

jy757443 jy757443 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这个例子是在帮助文档里面抄的,所以抄出问题了(哭)。
主要是public void Read_Callback(IAsyncResult ar)里面有些代码不执行,并且我也想不过为什么不执行。
请大家指教
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace ConsoleApplication1
{
public class StateObject
{
public Socket workSocket = null;
public const int BUFFER_SIZE = 1024;
public byte[] buffer = new byte[BUFFER_SIZE];
public StringBuilder sb = new StringBuilder();
}
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("10.254.254.36", 23);
StateObject state = new StateObject();
state.workSocket = socket;
socket.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(Read_Callback), state);
}
public static void Read_Callback(IAsyncResult ar)
{
StateObject so = (StateObject)ar.AsyncState;
Socket s = so.workSocket;
int read = s.EndReceive(ar);
if (read > 0)
{
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Read_Callback), so);//这里都会执行
}
else
{
if (so.sb.Length > 1)
{
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));//为什么这里永远都不执行了。很奇怪。
}
s.Close();
}
}
}
}
...全文
评论 7
收藏 已收藏
分享
返回顶部
jy757443
C# 111,130 成员 642,541 内容