带有windows窗体应用程序的C#socket服务器

带有windows窗体应用程序的C#socket服务器,c#,sockets,C#,Sockets,我搜索了很多,但互联网上所有的例子都是控制台应用程序。我曾尝试使用windows窗体的控制台应用程序示例,但当我调用socket.start窗体时,它会冻结,状态更改为(而不是响应)。我也尝试了多个线程,但也不成功。如果可能的话,请给我一些建议 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using Sys

我搜索了很多,但互联网上所有的例子都是控制台应用程序。我曾尝试使用windows窗体的控制台应用程序示例,但当我调用socket.start窗体时,它会冻结,状态更改为(而不是响应)。我也尝试了多个线程,但也不成功。如果可能的话,请给我一些建议

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

namespace mserver1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ServerClass sc = new ServerClass();
            sc.startServer(textBox1, richTextBox1);
        }
    }


    public class ServerClass
    {
        public void startServer(TextBox tb, RichTextBox rb)
        {

            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9939);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(ip);
            socket.Listen(20);
            rb.Text = rb.Text + "Waiting for client...";
            Socket client = socket.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

            rb.Text = rb.Text + "Connected with " + clientep.Address + " at port " + clientep.Port;

            string welcome = tb.Text;
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);

            rb.Text = rb.Text + "Disconnected from" + clientep.Address;
            client.Close();
            socket.Close();
        }
    }
}

谢谢。

您的应用程序将被阻止,直到按钮1\u单击返回

您需要生成一个工作线程来进行侦听。此外,不应将控件直接传递到工作线程。相反,您应该有一个回调,它将使用来自套接字通信的数据填充控件


查找有关后台工作人员的信息。这将使您到达需要的位置。

我也遇到了同样的问题,请按照我的服务器解决方案进行操作

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;


using System.Threading;

namespace SERVER_WIN
{
    public partial class Form1 : Form
    {

        //Declare and Initialize the IP Adress
        static IPAddress ipAd = IPAddress.Parse("10.1.42.31");

        //Declare and Initilize the Port Number;
        static int PortNumber = 8888;

        /* Initializes the Listener */
        TcpListener ServerListener = new TcpListener(ipAd, PortNumber);
        TcpClient clientSocket = default(TcpClient);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread ThreadingServer = new Thread(StartServer);
            ThreadingServer.Start();
        }

        private void THREAD_MOD(string teste)
        {
            txtStatus.Text += Environment.NewLine + teste;
        }

        private void StartServer()
        {
            Action<string> DelegateTeste_ModifyText = THREAD_MOD;            
            ServerListener.Start();
            Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
            clientSocket = ServerListener.AcceptTcpClient();
            Invoke(DelegateTeste_ModifyText, "Server ready!");

            while (true)
            {
                try
                {

                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[20];
                    networkStream.Read(bytesFrom, 0, 20);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                    string serverResponse = "Received!";
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                }
                catch
                {
                    ServerListener.Stop();
                    ServerListener.Start();
                    Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
                    clientSocket = ServerListener.AcceptTcpClient();
                    Invoke(DelegateTeste_ModifyText, "Server ready!");
                }

            }
        }
    }
}
对于客户,您需要设置一些控件; 两个文本视图(txtStatus和txtEnviar)和一个名为btnEnviar的按钮,就是它


您必须先运行服务器,然后才能运行客户端。如果需要停止客户端,请不要担心,您可以让服务器运行。

“我也尝试了多个线程,但也没有成功”-您是如何尝试的,您遇到了什么问题?在StartServer()返回之前,应用程序将没有响应,这取决于接受传入连接并发回数据所需的时间。(默认情况下套接字是阻塞的)我在button1\u Click事件中调用了线程。问题是相同的表单冻结了。我尝试了你的解决方案,但也冻结了。我只是复制和粘贴代码,没有任何更改
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;
using System.IO;

namespace CLIENT_WIN
{
    public partial class Form1 : Form
    {
        TcpClient tcpclnt = new TcpClient();

        //Declare and Initialize the IP Adress
        IPAddress ipAd = IPAddress.Parse("10.1.42.31");

        //Declare and Initilize the Port Number;
        int PortNumber = 8888;

        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine("Connecting.....");
            try
            {
                tcpclnt.Connect(ipAd, PortNumber);
                txtStatus.Text += Environment.NewLine + "Connected";
                txtStatus.Text += Environment.NewLine + "Enter the string to be transmitted";
            }
            catch { }
        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            String str = txtEnviar.Text + "$";
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);

            txtStatus.Text += Environment.NewLine + "Transmitting...";
            //Console.WriteLine("Transmitting.....");

            stm.Write(ba, 0, ba.Length);

            byte[] bb = new byte[100];
            int k = stm.Read(bb, 0, 100);

            string Response = Encoding.ASCII.GetString(bb);

            txtStatus.Text += Environment.NewLine + "Response from server: " + Response;

        }
    }
}