socket:发送和接收,无需等待

时间:2016-04-07 19:11:54

标签: c# winforms sockets

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

主机:

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();
        }
    }
}

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

1 个答案:

答案 0 :(得分:1)

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

这样的事情:

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()函数中放入一个无限循环。

希望这有帮助。