-2

我一直被困在这里.....我正在创建一个聊天服务器 Windows 应用程序,它将托管并且所有客户端都将注册

让我解释一下我的场景,当我启动聊天服务器时.....我使用了 TextBox 名称 ChatTextBox,我尝试在其中获取所有注册的客户端 IP 地址

但是当我尝试在服务器上注册客户端时,它显示跨线程操作无效,如何解决?????

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

namespace Myservercheck
{
public partial class Form2 : Form
{
    TcpListener myli;
    TcpClient clientSocket = default(TcpClient);
    string s=string.Empty;

    public Form2(TcpListener tc)
    {
        myli = tc;
        InitializeComponent();

    }

    private void Form2_Load(object sender, EventArgs e)
    {
        IPlistBox.Items.Add(myli.LocalEndpoint.ToString());
        chattextBox.Text= "Chat server started on selected IP & Port Number:\n"+myli.LocalEndpoint.ToString();
        chattextBox.AppendText("\n");
        chattextBox.AppendText("Waiting for connections............\n");
        myli.Start();
       Thread thread1 = new Thread(listern);
       thread1.Start();
        chattextBox.AppendText("\n");


    }


    public void listern()
    {
        while (true)
        {

            clientSocket = myli.AcceptTcpClient();
            IPAddress tempAddress = ((IPEndPoint)(clientSocket.Client.RemoteEndPoint)).Address;
            chattextBox.Text = tempAddress.ToString();
            chattextBox.AppendText("Connection accepted from:" + s);
        }
        }
    }




    }
4

1 回答 1

1

您需要调用表单控件上的方法来委托给表单的线程。您只能从创建表单的同一线程访问表单控件。

public void listern() {
    while (true) {
        clientSocket = myli.AcceptTcpClient;
        IPAddress tempAddress = ((IPEndPoint)(clientSocket.Client.RemoteEndPoint)).Address;
        UpdateChattextBox(tempAddress.ToString, "Connection accepted from:" + s);     
    }
}

public void UpdateChattextBox(string address, string message) {
    if ((chattextBox.InvokeRequired == true)) {
        this.invoke(UpdateCattextBox, address, message);
    }
    else {
        chattextBox.Text = tempAddress.ToString;
        chattextBox.AppendText(("Connection accepted from:" + s));
    }
}
于 2013-03-07T12:54:26.330 回答