虽然(真实)只发生一次没有错误

时间:2014-12-23 00:30:42

标签: c# multithreading sockets

非常直截了当的问题。我通过按钮按下动作创建的线程中的while循环只发生一次并且"这个"再也不会重复了。它确实接收到第一条消息,但是由于while循环被卡住,因此未收到将来的消息。第一条消息打印出来。

打印消息后,切换循环也不会发生。

        private void button1_Click(object sender, EventArgs e)
    {
        Thread Listener = new Thread(ServerListener);
        Listener.Start();
    }



    public void ServerListener()
    {
        byte[] buf;
        NetworkStream serverStream = clientSocket.GetStream();
        while (true)
        {
            Console.WriteLine("this");
            if (serverStream.DataAvailable)
            {
                buf = new byte[clientSocket.ReceiveBufferSize];
                serverStream.Read(buf, 0, buf.Length);
                string stringdata = Encoding.ASCII.GetString(buf);
                Console.WriteLine("Received message: " + stringdata);

                switch (stringdata)
                {
                    case "ping":
                        buf = Encoding.ASCII.GetBytes("pong");
                        Console.WriteLine("Sent pong");
                        serverStream.Write(buf, 0, buf.Length);
                        serverStream.Flush();
                        break;
                    case "handshake":
                        buf = Encoding.ASCII.GetBytes("lol");
                        Console.WriteLine("Sent confirmation");
                        serverStream.Write(buf, 0, buf.Length);
                        serverStream.Flush();
                        break;
                }

            }
        }
    }

我相信有人会来告诉我使用任务。我知道如何使用任务,但我发现任务与长期运行与普通线程之间没有区别。

2 个答案:

答案 0 :(得分:0)

好的,我现在正在发布有效的代码

客户:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        TcpClient clientSocket;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            clientSocket = new TcpClient("127.0.0.1", 8001); // Note the change
            Thread Listener = new Thread(ServerListener);
            Listener.Start();
        }

        public void ServerListener()
        {
            byte[] buf;
            Console.WriteLine("Thread started");

            NetworkStream serverStream = clientSocket.GetStream();
            while (true)
            {
                Console.WriteLine("this");
                if (serverStream.DataAvailable)
                {
                    buf = new byte[clientSocket.ReceiveBufferSize];
                    serverStream.Read(buf, 0, buf.Length);
                    string stringdata = Encoding.ASCII.GetString(buf);
                    Console.WriteLine("Received message: " + stringdata);

                    switch (stringdata)
                    {
                        case "ping":
                            buf = Encoding.ASCII.GetBytes("pong");
                            Console.WriteLine("Sent pong");
                            serverStream.Write(buf, 0, buf.Length);
                            serverStream.Flush();
                            break;
                        case "handshake":
                            buf = Encoding.ASCII.GetBytes("lol");
                            Console.WriteLine("Sent confirmation");
                            serverStream.Write(buf, 0, buf.Length);
                            serverStream.Flush();
                            break;
                    }

                }
            }
        }
    }
}

服务器:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                IPAddress IP = IPAddress.Parse("127.0.0.1");

                TcpListener Listener = new TcpListener(IP, 8001);
                Listener.Start();

                Socket s = Listener.AcceptSocket();
                Console.WriteLine("Conected");
                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes("ping"));
                Console.WriteLine("Data sent");

                s.Close();
                Listener.Stop();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }

            Console.ReadKey();
        }
    }
}

问题你:

我认为这是您的SERVER或代码中没有向我们展示的。在Server上面作为控制台应用程序运行,客户端作为winform应用程序运行。

答案 1 :(得分:0)

我了解到我需要构建我的传出数据。有关框架的示例,请查看以下代码。框架告诉接收器预期会有多少数据。

   public void SendResponse(int command, Object[] args)
    {
        if (ClientSocket == null)
        {
            Console.WriteLine("Command: ClientSocket");
            return;
        }
        var serverStream = this.ClientSocket.GetStream();
        if (!serverStream.CanRead || !serverStream.CanWrite)
        {
            Console.WriteLine("Command: serverStream Error");
            return;
        }
        byte[] toSend = null;
        switch (command)
        {
            // 0 - genneral, 1 - handshake response
            case 0:
                toSend = Encoding.ASCII.GetBytes(args[0].ToString());
                break;
            case 1:
                Rectangle bounds = Screen.GetBounds(Point.Empty);
                using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555))
                {
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                    }
                    toSend = ImageToByte(bitmap);
                }
                break;
        }

        try
        {
//--- Framing occurs here mainly
            byte[] bufferedToSend = new byte[toSend.Length + 4];
            byte[] lengthOfSend = BitConverter.GetBytes(toSend.Length);
            Array.Copy(lengthOfSend, bufferedToSend, 4);
            toSend.CopyTo(bufferedToSend, 4);
            serverStream.Write(bufferedToSend, 0, bufferedToSend.Length);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }