因此,在过去4天中,我已经使用TCPListener和TCPClient进行了测试。我已经轻松创建了一个独立的服务器/侦听器和一个独立的发件人/客户端。现在,我试图在一个应用程序中完成所有操作,但是当我尝试启动服务器时,整个应用程序将挂起。我不明白为什么它与我在不同应用程序中几乎一样的代码。
我尝试了它的多种变体并观看了多个教程,但是由于实际上我已经使用过相同的代码,所以我不知道发生了什么。
一旦我单击开始按钮触发StartButton_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 ChatTest2
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
ServerIPtextBox.Text = address.ToString();
}
}
}
private void StartButton_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void ConnectButton_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(ClientIPtextBox.Text), int.Parse(ClientPorttextBox.Text));
try
{
client.Connect(IpEnd);
if (client.Connected)
{
ChatScreentextBox.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.ChatScreentextBox.Invoke(new MethodInvoker(delegate ()
{
ChatScreentextBox.AppendText("You:" + recieve + "\n");
}));
recieve = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine(TextToSend);
this.ChatScreentextBox.Invoke(new MethodInvoker(delegate ()
{
ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending failed");
}
backgroundWorker2.CancelAsync();
}
private void SendButton_Click(object sender, EventArgs e)
{
if (MessagetextBox.Text != "")
{
TextToSend = MessagetextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
MessagetextBox.Text = "";
}
}
}
答案 0 :(得分:1)
DSLContext
此行阻止了您的UI线程。
我会尝试使用async和await。
client = listener.AcceptTcpClient();
希望对您有帮助。