本帖最后由 qiumanlover 于 2013-5-29 13:47 编辑
服务端和客户端是一样的程序,即只有一个程序,开两个,绑定不同地址,然后实现通讯。
发送消息是通过监听TextBox的KeyDown事件实现的,接收消息是放在线程里的
现在的问题是:两边的程序只能接受一次对方的消息,此后就收不到了
如果将接受消息的方法放在按键事件里,则会卡住输入框,直到收到对面的消息
源码如下:- using System;
- using System.Text;
- using System.Windows.Forms;
- using System.Net.Sockets;
- using System.Net;
- using System.Threading;
- namespace UDP_SYN
- {
- public partial class UDPClient : Form
- {
- private IPEndPoint localIpe = null; //本地节点
- private Socket localSock = null; //绑定本地节点的套接字
- private static IPEndPoint remoteIpe = null; //远程结点
- private EndPoint Remote = null; //用于接收消息的抽象对象结点
- private byte[] sendbuff = new byte[1024]; //发送缓冲区
- private byte[] recvbuff = new byte[1024]; //接收缓冲区
- private int msgLen; //接收的数据的字节长度
- public UDPClient()
- {
- CheckForIllegalCrossThreadCalls = false;
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false; //关闭文本框的跨线程检查
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- button1.Enabled = true;
- txtSend.Enabled = false;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- localIpe = new IPEndPoint(IPAddress.Parse(txtLocalIP.Text.ToString().Trim()),
- Convert.ToInt32(txtLocalPort.Text.ToString().Trim()));
- localSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- remoteIpe = new IPEndPoint(IPAddress.Parse(txtRemoteIP.Text.ToString().Trim()),
- Convert.ToInt32(txtRemotePort.Text.ToString().Trim()));
- localSock.Bind(localIpe);
- Thread startThrd = new Thread(new ThreadStart(RecvThrd));
- startThrd.IsBackground = true;
- startThrd.Start();
- //处理按键之后的页面布局,阻止修改配置
- txtSend.Enabled = true;
- button1.Enabled = false;
- txtLocalIP.Enabled = false;
- txtLocalPort.Enabled = false;
- txtRemoteIP.Enabled = false;
- txtRemotePort.Enabled = false;
- txtSend.Focus();
- }
- //按下回车键发送消息,并显示在自己的接收消息窗口
- private void txtSend_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Enter)
- {
- try
- {
- sendbuff = Encoding.ASCII.GetBytes(txtSend.Text.ToString());
- localSock.SendTo(sendbuff, remoteIpe);
- txtRecv.AppendText(localSock.LocalEndPoint.ToString() + " " +
- DateTime.Now.ToString() + " " + remoteIpe.ToString()
- + "\r\n\t" + txtSend.Text.ToString() + "\r\n");
- SendKeys.Send("{BackSpace}");
- txtSend.Clear();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
- //接收消息的方法,放入线程,防止阻塞当前窗口
- private void RecvThrd()
- {
- Remote = (EndPoint)(remoteIpe);
- msgLen = localSock.ReceiveFrom(recvbuff, ref Remote);
- Remote = (EndPoint)(remoteIpe);
- ShowMsg(Encoding.ASCII.GetString(recvbuff, 0, msgLen));
- }
- public void ShowMsg(string str)
- {
- txtRecv.AppendText(Remote.ToString() + " " + DateTime.Now.ToString()
- + " " + Remote.ToString() + "\r\n\t" + str + "\r\n");
- }
- }
- }
复制代码 |
|