首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重用SocketAsyncEventArgs在sendAsync中的无限循环

重用SocketAsyncEventArgs在sendAsync中的无限循环
EN

Stack Overflow用户
提问于 2016-07-14 22:52:22
回答 1查看 336关注 0票数 0

我正在学习套接字,我有一个程序:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace client
{
public class MyClient
{
    static ManualResetEvent _clientDonte = new ManualResetEvent(false);
    private static Socket _clientSocket;
    private SocketAsyncEventArgs _connectSocketEventArg;
    private CancellationTokenSource _cancelationTokenSource;

    public MyClient()
    {

    }

    public void Start(string address, uint port)
    {
        _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse(address), (int)port);
        _connectSocketEventArg = new SocketAsyncEventArgs();

        _connectSocketEventArg.Completed += ConnectSocketEventArgCompleted;
        _connectSocketEventArg.RemoteEndPoint = serverEP;
        _connectSocketEventArg.UserToken = _clientSocket;

        _clientSocket.ConnectAsync(_connectSocketEventArg);
        _clientDonte.WaitOne();
        Console.WriteLine("DAJESZ KURWA, NAPISZ COS!");
        while (true)
        {
            SendFromConsole();
        }

    }

    private void SendFromConsole()
    {
        var message = Console.ReadLine();
        var buff = Encoding.ASCII.GetBytes(message);
        _connectSocketEventArg.SetBuffer(buff, 0, buff.Length);
        _clientSocket.SendAsync(_connectSocketEventArg);
    }

    private void ConnectSocketEventArgCompleted(object sender, SocketAsyncEventArgs e)
    {
        switch (e.LastOperation)
        {
            case SocketAsyncOperation.Connect:
                ProcessConnect(e);
                break;
            case SocketAsyncOperation.Receive:
                ReceiveAsync(e);
                break;
            case SocketAsyncOperation.Send:
                SendAsync(e);
                break;
            default:
                throw new Exception("Invalid operation completed");
        }
    }

    private void SendAsync(SocketAsyncEventArgs e)
    {
        if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
        {
            Socket sock = e.UserToken as Socket;
            bool willRaiseEvent = sock.SendAsync(e);
            if (!willRaiseEvent)
            {
                ReceiveAsync(e);

            }
        }

    }

    private void ReceiveAsync(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            Console.WriteLine("SERVER>>: {0}", Encoding.ASCII.GetString(e.Buffer));
            Socket sock = e.UserToken as Socket;
        }
    }

    private void ProcessConnect(SocketAsyncEventArgs e)
    {
        _cancelationTokenSource = new CancellationTokenSource();
        Task.Factory.StartNew(ProgressConnect, _cancelationTokenSource.Token);

        if (e.SocketError == SocketError.Success)
        {
            Thread.Sleep(701);
            _cancelationTokenSource.Cancel();
            Console.WriteLine("Nawiazano polaczenie!");
            _clientDonte.Set();
        }
        else if (e.SocketError == SocketError.SocketError)
        {
            Console.WriteLine("Nie udalo sie! nacisnij cos by wyjsc");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }

    private void ProgressConnect()
    {
        while (!_cancelationTokenSource.Token.IsCancellationRequested)
        {
            Console.Write(".");
            _cancelationTokenSource.Token.WaitHandle.WaitOne(700);
        }
    }
}
}

它应该允许写入消息、发送消息并等待异步响应。不幸的是,当我发送第一条消息时,它会陷入无限的发送循环。我看过Reusing SocketAsyncEventArgs with ReceiveAsync results in infinite loop这个话题,但没有用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-14 23:15:01

我从来没有用过这个建筑,但是;

发送的无限循环可能是,您从未检查要发送的字节是否已发送。您可能需要检查BytesTransferred属性是否等于要发送的字节。

另外,您正在使用手动重置事件阻塞当前线程。为什么不使用非异步Connect()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38385454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档