C#中Udp通信问题
我在C#中,用Udp实现网络通信,用计算机向一个端口发消息后,如果想从接受消息方再消息发回来,还需要什么链接吗?下面是我写的代码,有点问题,希望大家帮我改一下!窗体就是上面一个richtextbox1,下面一个richtextbox2,最下面一个接收按钮btnReceive,一个发送按钮btnSend。两个窗体结构是一样的!麻烦大家了!
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;
namespace 个人
{
public partial class 个人 : Form
{
UdpClient udpClient;
Thread thread;
public 个人()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
udpClient = new UdpClient(13579);
}
private void listen()
{
IPEndPoint iep = null;
while (true)
{
string sData = System.Text.Encoding.UTF8.GetString
(udpClient.Receive(ref iep));
this.richTextBox1.Text += sData;
}
}
private void btnSend_Click(object sender, EventArgs e)
{
richTextBox1.Text += richTextBox2.Text;
string temp = this.richTextBox2.Text;
byte[] bData = System.Text.Encoding.UTF8.GetBytes(temp);
udpClient.Connect(IPAddress.Parse("127.0.0.1"), 13579);
udpClient.Send(bData, bData.Length);
richTextBox2.Text = null;
richTextBox2.Focus();
}
private void btnReceive_Click(object sender, EventArgs e)
{
btnReceive.Enabled = false;
thread = new Thread(new ThreadStart(listen));
thread.IsBackground = true;
thread.Start();
}
private void 个人_FormClosing(object sender, FormClosingEventArgs e)
{
if (thread != null)
thread.Abort();
}
}
}
------------------------------------------
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;
namespace Udp聊天
{
public partial class 群 : Form
{
UdpClient udpClient;
Thread thread;
public 群()
{
udpClient = new UdpClient();
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
//udpClient = new UdpClient(13579);
}
private void btnSend_Click(object sender, EventArgs e)
{
richTextBox1.Text += '\n'+this.richTextBox2.Text;
string temp = this.richTextBox2.Text;
byte[] bData = System.Text.Encoding.UTF8.GetBytes(temp);
udpClient.Connect(IPAddress.Parse("127.0.0.1"), 13579);
udpClient.Send(bData, bData.Length);
richTextBox2.Text = null;
richTextBox2.Focus();
}
private void btnReceive_Click(object sender, EventArgs e)
{<