UDP发送消息的问题

springe 2009-05-23 11:03:10
各位大侠,小弟刚学c#不久,编了一个小小的程序,这个窗体程序可以运行,但是点击Button1的时候却没有任何反应,甚至没有响应,变成了一个死程序。请问,我这里出现了什么问题呢?由于不会上传图片:窗体是由2个TextBox控件和一个Button控件组成,在TextBox2上输入消息,在TextBox1上接受消息!希望众大侠多多帮忙!!感谢不尽!!
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;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int length;
string str;
byte[] bytes=new byte[1024];
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint myHost = new IPEndPoint(IPAddress.Any, 3050);
socket.Bind(myHost);
IPEndPoint remote = new IPEndPoint(IPAddress.Parse("196.128.0.102"), 3050);
socket.Connect(remote);
bytes = System.Text.Encoding.Unicode.GetBytes(TextBox2.Text);
socket.Send(bytes);
txtMain1.Text = TextBox1.Text + "\n" + System.DateTime.Now.ToString() + "\n" + "你说:" + TextBox2.Text;
while (true)
{
length = socket.Receive(bytes);
str = System.Text.Encoding.Unicode.GetString(bytes, 0, length);
TextBox1.Text = TextBox1.Text + str+"\n";
str = TextBox2.Text;
bytes = System.Text.Encoding.Unicode.GetBytes(str);
socket.Send(bytes);
}

}
}
}
...全文
90 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
springe 2009-05-23
  • 打赏
  • 举报
回复
你们可以帮我完善一下吗?可以发送消息就可以了
springe 2009-05-23
  • 打赏
  • 举报
回复
对!应该要加个判断了
beckfun 2009-05-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 springe 的回复:]
还有就是 while (true)
{
length = socket.Receive(bytes);
str = System.Text.Encoding.Unicode.GetString(bytes, 0, length);
TextBox1.Text = TextBox1.Text + str+"\n";
str = TextBox2.Text;
bytes = System.Text.Encoding.Unicode.GetBytes(str);
socket.Send(bytes);
}
这些…
[/Quote]这是一个死循环,你应该+个判断,然后break,
while (true) //循环接受数据流
{
length = socket.Receive(bytes); //获取接受的字节数
/**我自己加的**/
//if(length==0)
// break;
/*************/
str = System.Text.Encoding.Unicode.GetString(bytes, 0, length); //获取指定字节数的数据流并转换成字符串,
TextBox1.Text = TextBox1.Text + str+"\n"; //显示在TextBox1上
str = TextBox2.Text;
bytes = System.Text.Encoding.Unicode.GetBytes(str); //转化成字节流
socket.Send(bytes); //发送
}

可能解释上会有些差错
zealot1021 2009-05-23
  • 打赏
  • 举报
回复
加断点,按F10跟踪一下
springe 2009-05-23
  • 打赏
  • 举报
回复
还有就是 while (true)
{
length = socket.Receive(bytes);
str = System.Text.Encoding.Unicode.GetString(bytes, 0, length);
TextBox1.Text = TextBox1.Text + str+"\n";
str = TextBox2.Text;
bytes = System.Text.Encoding.Unicode.GetBytes(str);
socket.Send(bytes);
}
这些语句有什么用,用中文阐述一下可以吗?
springe 2009-05-23
  • 打赏
  • 举报
回复
没人会吗?

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧