【问题标题】:socket: send and receive without waitingsocket:无需等待即可发送和接收
【发布时间】:2016-07-28 20:44:53
【问题描述】:

我需要在两个应用程序之间发送和接收信息:

主持人:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace DATA_SENDER_HOST
{
    public partial class Form1 : Form
    {
        static Socket sck;
        static byte[] Buffer { get; set; }
        Socket accepted;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(0, 1234));
            sck.Listen(100);

            accepted = sck.Accept();
            Buffer = new byte[accepted.SendBufferSize];
            int bytesRead = accepted.Receive(Buffer);
            byte[] formatted = new byte[bytesRead];
            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string strData = Encoding.ASCII.GetString(formatted);
            if (strData == "1")
                panel1.BackColor = Color.Red;
            else if (strData == "2")
                panel1.BackColor = Color.Blue;
            sck.Close();
            accepted.Close();


        }
    }
}

客户:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace CLIENT
{
    public partial class Form1 : Form
    {
        static Socket sck;
        IPEndPoint localEndPoint;

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            sck.Connect(localEndPoint);
            string text = "1";
            byte[] data = Encoding.ASCII.GetBytes(text);
            sck.Send(data);

            sck.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            sck.Connect(localEndPoint);
            string text = "2";
            byte[] data = Encoding.ASCII.GetBytes(text);
            sck.Send(data);

            sck.Close();
        }
    }
}

但在这种情况下,主机必须等待来自客户端的数据;
我的问题是:如何检测客户端何时发送而不等待(等待我的意思是在“accepted = sck.Accept()”之前的“sck.Listen(100)”)?

【问题讨论】:

标签: c# winforms sockets


【解决方案1】:

执行此操作的传统方法是在另一个线程中以无限循环执行 Listen()(如果您尝试构建具有无限连接的服务器),然后在触发侦听时触发代码。

所以是这样的:

private void button1_Click(object sender, EventArgs e)
{

    sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sck.Bind(new IPEndPoint(0, 1234));

    System.Threading.Thread T = new System.Threading.Thread((new System.Threading.ThreadStart(Listener)));

    T.Start();
}

private void Listener()
{
    sck.Listen(100);
    accepted = sck.Accept();
    Buffer = new byte[accepted.SendBufferSize];
    int bytesRead = accepted.Receive(Buffer);
    byte[] formatted = new byte[bytesRead];
    for (int i = 0; i < bytesRead; i++)
    {
        formatted[i] = Buffer[i];
    }
    string strData = Encoding.ASCII.GetString(formatted);
    panel1.Invoke((MethodInvoker)delegate
    {
        if (strData == "1")
            panel1.BackColor = Color.Red;
        else if (strData == "2")
            panel1.BackColor = Color.Blue;
    });
    sck.Close();
    accepted.Close();
}

如果你想让它无限等待套接字(就像大多数此类事情的用例一样),你可以在 Listener() 函数中放置一个无限循环。

希望这会有所帮助。

【讨论】: