从.net socket中的无限循环中获取变量 [英] get variable from infinite loop in .net socket

查看:421
本文介绍了从.net socket中的无限循环中获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在使用.NET同步套接字将数据从客户端发送到服务器。

我需要从StartListening()获取数据在Main()中使用它的方法但是

变量数据在无限循环内(而(true))。

请帮忙吗?

这是服务器代码:

Hello,
I''m using .NET synchronous socket to send data from a client to server.
I need to get the data from the StartListening() method to use it in the Main() but
the variable data is inside an infinite loop ( while(true)).
Any help please?
This is the server code :

using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;


public class SynchronousSocketListener
{

    byte[] bytes = new Byte[1024];
    IPHostEntry ipHostInfo;
    IPAddress ipAddress ;
    IPEndPoint localEndPoint;

    Socket listener;
   // Incoming data from the client.
    public static string data = null;

    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    private volatile bool _shouldStop;

    public  void InitializeListening()
    {
        // Data buffer for incoming data.
 
        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
         ipHostInfo = Dns.Resolve("localhost");
         ipAddress = ipHostInfo.AddressList[0];
         localEndPoint = new IPEndPoint(ipAddress, 11007);

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

    public void StopListening()
    {
        _shouldStop = true;
        byte[] msg = Encoding.ASCII.GetBytes("please stop!");
        // Create a TCP/IP  socket.
        Socket sender = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
            // Connect the socket to the remote endpoint. Catch any errors.
            try {
                sender.Connect(localEndPoint);
                // Send the data through the socket.
                int bytesSent = sender.Send(msg);
                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            } 
    }

    public  void StartListening()
    {
        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try
        {

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Thread is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                
                // An incoming connection needs to be processed.
                if (_shouldStop)
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                    break;
                }
                data = null;
                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }

                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);

                // Echo the data back to the client.
                //byte[] msg = Encoding.ASCII.GetBytes(data);
                byte[] msg = Encoding.ASCII.GetBytes("Salam !");
                handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

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

    public static int Main(String[] args)
    {
        Console.WriteLine("I am the Synchronous Socket Server\n");
        SynchronousSocketListener pServer = new SynchronousSocketListener();
        pServer.InitializeListening();
        Thread serverkerThread = new Thread(pServer.StartListening);
        serverkerThread.Start();
        // Loop until server thread activates.
        while (!serverkerThread.IsAlive) ;

        Console.WriteLine("listening thread sevice started...\n");

        Console.WriteLine("\nPress Q when you want to quit...\n");
        int car;
        do
        {
            Thread.Sleep(100);
            car = Console.Read();
            if (car == 81)
            {
                // Request that the worker thread stop itself:
                pServer.StopListening();

                // Use the Join method to block the current process 
                // until the object's thread terminates.
                serverkerThread.Join();
                break;
            }
        } while (true);

        Console.WriteLine("listening thread sevice stopped and program will be exited...\n");

        return 0;
    }
}

推荐答案

除了数据初始化为 null 并且抛出连接时会出现异常+ = (初始化为 string.Empty ),我没有看到问题。

数据应该可以从 Main 访问。

然而,你需要/需要在线程之间使用某种形式的同步。
Other than the problem that data is initialized to null and will throw an exception when you concatenate to it with += (initialize to string.Empty instead), I don''t see the problem right off.
data should be accessible from the Main.
However, you''ll want/need to use some form of synchronization between the threads.


这篇关于从.net socket中的无限循环中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆