C# 关于UDP通信的问题
打算写个局域网QQ作为练习
刚开始写就遇到问题
代码贴下
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.Threading;
using System.Net;
namespace UDPclient_04
{
public partial class Form1 : Form
{
UDPClient udp = new UDPClient();
public delegate void Dele(string str);
public Dele dele;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// textBox1.Text= udp.GetMyIpAddress().ToString();
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips)
{
richTextBox1.Text += ip.ToString()+"\n";
}
//textBox1.Text = ips[3].ToString();
}
private void button2_Click(object sender, EventArgs e)
{
udp.send(textBox2.Text);
}
private void button3_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(receive));
th.IsBackground = true;
th.Start();
}
public void receive()
{
while(true)
{
richTextBox1.Invoke(dele,udp.receive_any());
}
}
private void Form1_Load(object sender, EventArgs e)
{
dele = new Dele(showmessage);
}
public void showmessage(string str)
{
richTextBox1.Text+=str+"\n";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPclient_04
{
class UDPClient
{
public IPEndPoint ipendpoint = null;
public IPAddress ipaddress = null;
public UdpClient udp;
public UDPClient()
{
ipendpoint = new IPEndPoint(IPAddress.Parse("192.168.1.88"), 11111);
udp = new UdpClient(ipendpoint);
}
public void send(string str)
{
byte[] by = Encoding.Default.GetBytes(str);
udp.Send(by,by.Length,ipendpoint);
}
public IPAddress GetMyIpAddress()
{
return Dns.GetHostAddresses("")[0];
}
public string receive_any()
{
IPAddress i = IPAddress.Any;
IPEndPoint a = new IPEndPoint(i, 11111);
return Encoding.Default.GetString(udp.Receive(ref a));
}
}
}