2

我正在尝试在 winforms 中构建一个基本的服务器客户端应用程序。但是服务器什么也不做。如果我可以这么说,只是有点打开并挂起。我究竟做错了什么。我制作的应用程序如下:Server Winform

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;
using System.IO;

namespace ServerWinForms
{
    public partial class Form1 : Form
    {
        public delegate void AddText(TcpClient tcp, RichTextBox rtb);
        public AddText myDelegate;
        Thread myThread;

        public Form1()
        {
            InitializeComponent();

            myDelegate = new AddText(ClientSession);
        }

        void begin(Object obj)
        {
            var loaclAddress = IPAddress.Parse("127.0.0.1");
            var tcpListener = new TcpListener(loaclAddress, 81);
            tcpListener.Start();

            while (true)
            {
                var tcpClient = tcpListener.AcceptTcpClient();

                Form1 myForm1 = (Form1)obj;
                myForm1.Invoke(myForm1.myDelegate);

                //rtb.AppendText("Waiting for connection ");
                // Console.WriteLine("Waiting for a connection");


                //rtb.AppendText("Client Accepted ");
                //Console.WriteLine("Client Accepted");

                /*Thread thread = new Thread(() => ClientSession(tcpClient))
                {
                    IsBackground = true
                };

                thread.Start();
                //Console.WriteLine("Client Session thread started");
                */
            }
        }

        private static bool tryRead(Stream stream, byte[] buffer, int offset, int count)
        {
            int bytesRead;
            while (count > 0 && (bytesRead = stream.Read(buffer, offset, count)) > 0)
            {
                offset += bytesRead;
                count -= bytesRead;
            }
            return count == 0;
        }

        public static void ClientSession(TcpClient tcpClient, RichTextBox rtb)
        {
            const int totalByteBuffer = 4096;
            byte[] buffer = new byte[256];
            // UC ucObj = new UC();
            using (var networkStream = tcpClient.GetStream())
            using (var bufferedStream = new BufferedStream(networkStream, totalByteBuffer))
                while (true)
                {
                    if (!tryRead(bufferedStream, buffer, 0, 1))
                    {
                        break;
                    }
                    byte messageLen = buffer[0];
                    if (!tryRead(bufferedStream, buffer, 1, messageLen))
                    {
                        break;
                    }
                    var message = Encoding.ASCII.GetString(buffer, 1, messageLen);

                    //Console.WriteLine(/*"Message Recieved: {0}", */ message);
                    RichTextBox rcb = new RichTextBox();
                    rtb.AppendText(message);

                }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            myThread = new Thread(begin);
            myThread.Start(this);
            //begin();
        }
    }
}

客户端 Winform(虽然我相信这里一切正常,但仍然......)

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.IO;

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }


        private static byte[] msg2ByteArray(string message, Encoding enc)
        {
            var byteCount = enc.GetByteCount(message);
            if (byteCount > byte.MaxValue)
            {
                throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
            }
            var byteArray = new byte[byteCount + 1];
            byteArray[0] = (byte)byteCount;
            enc.GetBytes(message, 0, message.Length, byteArray, 1);
            return byteArray;
        }

        void sendMsg()
        {
            String message;
            using (var tcpClient = new TcpClient())
            {
                tcpClient.Connect("127.0.0.1", 81);
                using (var networkStream = tcpClient.GetStream())
                using (var bufferedStream = new BufferedStream(networkStream))
                {
                    //while (true)
                    //{
                        byte[] buffer = new byte[256];
                        //Console.WriteLine("Write Message");
                        message = richTextBox.Text;
                        var byteArray = msg2ByteArray(message, Encoding.ASCII);
                        bufferedStream.Write(byteArray, 0, byteArray.Length);
                        bufferedStream.Flush();
                    //}

                }
            }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            sendMsg();
        }


    }
}
4

1 回答 1

2

kewal,你的代码看起来不错,你的程序也很好。我也喜欢你分享所有的代码,当我需要询问几乎所有被要求这样做的人时,这是最令人沮丧的。

  1. 现在解决问题。你 tcpListener.Start();在你的服务器中使用。我们可以在这里阅读:

    “如果收到连接请求,Start 方法会将请求排队并继续侦听其他请求,直到您调用 Stop 方法”

    我相信你想要的是使用AcceptSocket()方法 - 在这里阅读

  2. 我可以建议:使用不同的端口。已占用少量端口,可能无法正常工作。我认为 81 如果用于 http,虽然我不确定

编辑 3. 对于客户端使用这个MSDN 示例来查看基本示例是否适合您

于 2013-08-14T08:12:21.550 回答