请求连接的代码在这里:
private void button1_Click(object sender, EventArgs e)
{
try
{
int port = int.Parse(textBox2.Text);
client = new TcpClient();
IPAddress remoteIP = IPAddress.Parse(textBox1.Text);
client.Connect(remoteIP, port);
statusBar1.Text = "已经连接到服务器";
Thread thread = new Thread(new ThreadStart(ReceiveData));
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
int port = int.Parse(textBox2.Text);
client = new TcpClient();
IPAddress remoteIP = IPAddress.Parse(textBox1.Text);
client.Connect(remoteIP, port);
statusBar1.Text = "已经连接到服务器";
Thread thread = new Thread(new ThreadStart(ReceiveData));
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
delegate void AddListBoxItemCallback(string text);
AddListBoxItemCallback listBoxCallback;
public Form1()
{
InitializeComponent();
listBoxCallback = new AddListBoxItemCallback(AddListBoxItem);
}
private void AddListBoxItem(string text)
{
//如果listBoxReceive被不同的线程访问则通过委托处理;
if (listBox1.InvokeRequired)
{
this.Invoke(listBoxCallback, text);
}
else
{
listBox1.Items.Add(text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
{
thread.Abort();
client.Close();
}