为什么列表框没有在ASP.NET中通过线程显示新添加的项目?

时间:2018-04-17 20:13:12

标签: c# asp.net multithreading listbox listboxitem

我是ASP.NET的新手,我试图在网上制作聊天应用程序。 我使用System.Net.Sockets进行服务器和客户端之间的通信。使用当前版本的应用程序,我可以将数据从客户端发送到服务器,并将数据从服务器发送到客户端。客户端使用线程获取数据,并且线程中有一个循环以连续获取数据。问题是我从服务器到客户端获取数据,并且它被添加到列表框项目,但它没有显示列表框中的数据。我认为问题是因为使用了线程或循环。

客户代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace Client_s__Web_2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        static int port = 13000;
        static string IpaAddress = "127.0.0.1";
        static Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpaAddress), port);
        static string client_ismi = "";
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ClientSocket.Connect(ep);
            ListBox1.Items.Add("Client is connected.");
            byte[] isim = new byte[1024];
            int size = ClientSocket.Receive(isim);
            client_ismi = System.Text.Encoding.ASCII.GetString(isim, 0, size);
            Response.Redirect("WebForm1.aspx");
            ListBox1.Items.Add("The name that server has given: " + client_ismi);
            System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;

            ThreadStart st = new ThreadStart(get_data);
            Thread thread = new Thread(st);
            thread.Start();
        }
        public void get_data()
        {
            while (true)
            {
                byte[] MsgFromServer = new byte[1024];
                int size1 = ClientSocket.Receive(MsgFromServer);
                ListBox1.Items.Add("Server: " + System.Text.Encoding.ASCII.GetString(MsgFromServer, 0, size1));
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            string messageFromClient = null;
            messageFromClient = client_ismi + ": " + TextBox1.Text;
            TextBox1.Text = "";
           ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes(messageFromClient), 0, messageFromClient.Length, SocketFlags.None);
        }
    }
}

客户代码Aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Client_s__Web_2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Panel ID="Panel1" runat="server" DefaultButton = "Button2">
    <table>
        <tr>
            <td>

            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Start" OnClick="Button1_Click" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:ListBox ID="ListBox1" runat="server" Width ="700px" Height="500px"></asp:ListBox>
            </td>
            <td>

            </td>
        </tr>
        <tr>
            <td>
                <asp:TextBox ID="TextBox1" runat="server" Width ="700px" Height="50px"></asp:TextBox>
            </td>
            <td>
                <asp:Button ID="Button2" runat="server" Text="Send" OnClick="Button2_Click" />
            </td>
        </tr>
        <tr>
            <td>

            </td>
            <td>
                <asp:Button ID="Button3" runat="server" Text="Refresh" OnClick="Button3_Click" />
            </td>
        </tr>
    </table>
    </asp:Panel>
    </div>
    </form>
</body>
</html>

服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Main_Server
{
    class Program
    {

        static List<string> names = new List<string>();
        static List<Socket> clients = new List<Socket>();
        static Program p = new Program();
        static int counter = 0;
        static void Main(string[] args)
        {
            int port = 13000;
            string IpAddress = "127.0.0.1";
            Socket ServerListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), port);
            ServerListener.Bind(ep);
            ServerListener.Listen(100);
            Console.WriteLine("Server is listening");
            Socket ClientSocket = default(Socket);


            while(true)
            {
                counter++;
                ClientSocket = ServerListener.Accept();
                clients.Add(ClientSocket);

                string msgstr = "Guest_" + Convert.ToString(counter);
                names.Add(msgstr);
                byte[] msg = Encoding.ASCII.GetBytes(msgstr);
                int size = msg.Length;
                ClientSocket.Send(msg, 0, size, SocketFlags.None);
                Console.WriteLine(msgstr + " has connected");
                Thread UserThread = new Thread(new ThreadStart(() => p.User(counter - 2, msgstr)));
                UserThread.Start();
            }
        }
        public void User(int bulunan_client,string username)
        {
            while (true)
            {
                byte[] msg = new byte[1024];
                int size = clients[bulunan_client].Receive(msg);
                try
                {
                    if (System.Text.Encoding.ASCII.GetString(msg, 0, size).Substring(System.Text.Encoding.ASCII.GetString(msg, 0, size).Length - 10) == "disconnect")
                    {
                        names.Remove(names[bulunan_client]);
                        clients.Remove(clients[bulunan_client]);
                        Console.WriteLine(username + " has disconnected.");
                        counter--;
                        break;
                    }
                    else if (System.Text.Encoding.ASCII.GetString(msg, 0, size).Substring(System.Text.Encoding.ASCII.GetString(msg, 0, size).Length - 7) == "connect")
                    {
                        string sending_names = "";


                        for (int i = 0; i < names.Count; i++)
                        {
                            sending_names += (names[i] + " ");
                        }
                        clients[bulunan_client].Send(System.Text.Encoding.ASCII.GetBytes(sending_names), 0, (System.Text.Encoding.ASCII.GetBytes(sending_names)).Length, SocketFlags.None);



                        continue;
                    }
                }
                catch
                {
                    break;
                }
                Console.WriteLine(System.Text.Encoding.ASCII.GetString(msg,0,size));
            }
        }
    }
}

注意:当我发送&#34; connect&#34;从客户端我应该得到连接客户端的名称。我将它们带到列表框项目但它们没有显示。我使用Windows窗体应用程序完成了这个程序,我根本没有遇到任何问题。

谢谢你们的帮助:)。

1 个答案:

答案 0 :(得分:0)

这里的问题是你启动一个线程并在控制台中返回...它有一个不阻止ui的点,但在Web应用程序中你不能这样做。

所以在这一行中,程序返回并呈现页面。

 ThreadStart st = new ThreadStart(get_data);
 Thread thread = new Thread(st);
 thread.Start();

稍后如果线程调用get_data,则没有页面可以再渲染任何内容......

所以解决方案是删除线程 - 只需包含线程的功能来填充数据。

我还注意到这个while (true)代码在死循环中被阻塞了。解决这个问题。