2

我想知道如果我在其他线程上同步运行我的应用程序是否异步获取字符串?

我实际上不知道如何使用 BeginSend/BeginReceive,所以我在不同的线程上使用了 socket.Send(...)、socket.Receive(...),这是否使我的应用程序模拟异步连接。

顺便说一句,如果字符串大于缓冲区的大小会发生什么?对于客户端,我使用了 telnet,但是 telnet 实际上会在字符串从键盘获取时立即发送,所以我实际上不能超过缓冲区的大小,但是如果我使用另一个发送完整字符串的客户端呢?有没有办法告诉程序我发送的比缓冲区允许的多(通过我的变量recv是socketReceive的结果)?

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace CSharp_Console_Application
{
    class Program
    {
        delegate Socket GetClients();
        static GetClients newClients;
        static List<Socket> clients;

        static ManualResetEvent allDone = new ManualResetEvent(false);

        static void Main(string[] args)
        {
            IPEndPoint serverIPEP = new IPEndPoint(IPAddress.Any, 9080);
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(serverIPEP);
            serverSocket.Listen(10);

            Console.WriteLine("Waiting for connections...");

            clients = new List<Socket>();

            newClients = () =>
                {
                    Socket clientSocket = serverSocket.Accept();
                    IPEndPoint clientIPEP = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Connected to {0}.", clientIPEP);

                    clients.Add(clientSocket);

                    SendString("Welcome to my server!", clientSocket);
                    return clientSocket;
                };

            while (true)
            {
                allDone.Reset();

                newClients.BeginInvoke((itfAR) =>
                    {
                        allDone.Set();

                        AsyncResult ar = (AsyncResult)itfAR;
                        GetClients invokedDelegate = (GetClients) ar.AsyncDelegate;

                        Socket clientSocket = invokedDelegate.EndInvoke(itfAR);
                        IPEndPoint clientIPEP = (IPEndPoint)clientSocket.RemoteEndPoint;

                        Console.WriteLine("Sent 'Welcome!' to {0}.", clientIPEP);

                        string currentString = "";
                        while (true)
                        {
                            currentString += ReceiveString(clientSocket);
                            if (currentString.Contains('\n'))
                            {
                                Console.Write(clientIPEP + " said: " + currentString);

                                List<Socket> clientsWithoutThis = new List<Socket>();
                                clientsWithoutThis.AddRange(clients);
                                clientsWithoutThis.Remove(clientSocket);
                                SendToAll(clientsWithoutThis, currentString);

                                currentString = "";
                            }
                        }
                    },
                    null);

                allDone.WaitOne();
            }
        }

        static void SendToAll(List<Socket> clients, string message)
        {
            byte[] data = new byte[1024];
            clients.ForEach(clientSocket =>
                {
                    IPEndPoint clientIPEP = (IPEndPoint)clientSocket.RemoteEndPoint;
                    data = Encoding.ASCII.GetBytes(clientIPEP + " said: " + message + "\r");
                    clientSocket.Send(data, data.Length, SocketFlags.None);
                });
        }

        static void SendString(string message, Socket clientSocket)
        {
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(message + "\n\r");
            clientSocket.Send(data, data.Length, SocketFlags.None);
        }

        static string ReceiveString(Socket clientSocket)
        {
            byte[] data = new byte[1024];
            int recv = clientSocket.Receive(data, data.Length, SocketFlags.None);

            if (recv < 1)
                return null;

            string receivedString = Encoding.ASCII.GetString(data, 0, recv);
            return receivedString;
        }
    }
}
4

1 回答 1

0

这样你ManualResetEvent的往往是无用的。一旦你阻塞了主线程,你就会在BeginInvoke调用的第一行释放set(). 然后您再次将其重置为等待状态,但另一个BeginInvoke调用将解除对代码的阻塞,而另一个调用BeginInvoke可能仍在运行。因此,最终您将有多个 BeginInvoke 线程,最终您将遇到多个异常或内存不足错误。

于 2013-06-26T10:57:19.723 回答