form_load里启用监听:
private void Form_Load(object sender, System.EventArgs e)
{
System.Threading.Thread recThread = new Thread(new ThreadStart(DisPlayChatInfo));
recThread.Start();
}
//DisPlayChatInfo显示监听到的消息
private void DisPlayChatInfo()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient();
// IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8085);
int port = 8085;
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("192.168.10.49"),port);
//receivingUdpClient.Connect(RemoteIpEndPoint);
while(true) 
{
try
{ // Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);  string returnData = Encoding.ASCII.GetString(receiveBytes); ChatList.Items.Add("消息来自:" + RemoteIpEndPoint.Address.ToString());
ChatList.Items.Add("消息内容:" + returnData.ToString());
System.Threading.Thread.Sleep(100);
}
catch ( Exception e )
{
Console.WriteLine(e.ToString()); 
}
}
}
//SentChatInfo发送消息
   private void SentChatInfo()
{
// Accepts the pending client connection and returns a socket for communciation.
int port = 8085;
string responseString = ChatTopic.Text;
string romoteServer = this.TP.Text.Trim();
using(MemoryStream ms = new MemoryStream())
{
BinaryWriter bw = new BinaryWriter(ms); 
byte[] temp =  System.Text.Encoding.ASCII.GetBytes(responseString);
bw.Write(temp);
byte[] data2Send = ms.ToArray();
int ret =0;
try
{
ret = new UdpClient().Send(data2Send,data2Send.Length,romoteServer,port);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}

}
}
================================================================
请教了!
会的人请给的代码也可以!

解决方案 »

  1.   

    System.Text.Encoding.UTF8.GetBytes(responseString);
    这样就可以识别所有的文字!
      

  2.   

    System.Text.Encoding.Unicode.GetString();
    可以识别中文
      

  3.   

    System.Text.Encoding.Unicode.GetString()不能识别中文的话,改成
    System.Text.Encoding.Default.GetString()
      

  4.   

    UTF-8和unicode是兼容的,一般不用UTF-7,它用于电子邮件。采用default时,会把utf-8流中的前3个字节去掉,具体什么不记得了……