读书人

一个UDP通讯的小程序各位帮小弟我看

发布时间: 2012-01-08 22:48:50 作者: rapoo

一个UDP通讯的小程序,各位帮我看看。
下面是我做的一个UDP通讯小程序,
开了两个线程,一个用于接收,一个用于发送,
用了两个UDPClient,一个用于发送,一个用于接收。
为什么单机运行两个程序会出错?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace UDP多线程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


public UdpClient receiveUdp;
public IPEndPoint receivePoint;
public int LocalPort=8080; //本地端口

public UdpClient sendUdp;
public IPEndPoint remotePoint;
public int RemotPort; //远程通讯端口

public string sendText; //发送命令文本

public Thread recvThread; //定义接收线程
public Thread checkSendThread; //定义检测发送线程





//接收
public void receive()
{
receiveUdp = new UdpClient(LocalPort);
IPAddress myip = IPAddress.Parse( "127.0.0.1 ");
receivePoint = new IPEndPoint(myip, LocalPort);


bool control = false;

try
{
while (!control)
{
byte[] recData = receiveUdp.Receive(ref receivePoint);
string str = Encoding.Unicode.GetString(recData);
richTextBox1.AppendText(str);
receiveUdp.Close();
control = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

//接收线程
public void receiveThread()
{
recvThread = new Thread(new ThreadStart(receive));
recvThread.Start();
}

private void Form1_Load(object sender, EventArgs e)
{
receiveThread();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{


recvThread.Abort();
checkSendThread.Abort();
}

//发送
public void send()
{
try
{
sendText = textBox1.Text;
IPAddress RemoteIP = IPAddress.Parse( "127.0.0.1 ");
RemotPort = 6060;
IPEndPoint remotePoint = new IPEndPoint(RemoteIP, RemotPort);

sendUdp=new UdpClient(remotePoint);

byte[] sendBytes = Encoding.Unicode.GetBytes(sendText);
sendUdp.Send(sendBytes, sendBytes.Length);
sendUdp.Close();
}
catch
{

}
}

//启动检测发送侦听线程
public void StartCheckSendListenerThread()
{
checkSendThread=new Thread(new ThreadStart(send));
checkSendThread.Start();
}

//发送按钮


private void button1_Click(object sender, EventArgs e)
{
StartCheckSendListenerThread();
}
}
}

[解决办法]
这是一个点对点通信的源代码,你看看:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace P2PChat
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;

private Thread th;
private TcpListener tcpl;
private bool listenerRun = true;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;


this.button1.Location = new System.Drawing.Point(24, 8);
this.button1.Name = "button1 ";
this.button1.Size = new System.Drawing.Size(75, 24);
this.button1.TabIndex = 0;
this.button1.Text = "开始监听 ";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
this.button2.Enabled = false;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Location = new System.Drawing.Point(192, 8);
this.button2.Name = "button2 ";
this.button2.Size = new System.Drawing.Size(75, 24);
this.button2.TabIndex = 1;
this.button2.Text = "停止监听 ";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button3.Location = new System.Drawing.Point(192, 168);
this.button3.Name = "button3 ";
this.button3.Size = new System.Drawing.Size(75, 24);
this.button3.TabIndex = 2;
this.button3.Text = "发送消息 ";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.textBox1.Location = new System.Drawing.Point(120, 40);
this.textBox1.Name = "textBox1 ";
this.textBox1.Size = new System.Drawing.Size(152, 21);
this.textBox1.TabIndex = 3;
this.textBox1.Text = " ";
//
// textBox2
//
this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.textBox2.Location = new System.Drawing.Point(16, 72);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2 ";
this.textBox2.Size = new System.Drawing.Size(256, 88);
this.textBox2.TabIndex = 4;
this.textBox2.Text = " ";
//
// richTextBox1
//
this.richTextBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.richTextBox1.ForeColor = System.Drawing.Color.SteelBlue;
this.richTextBox1.Location = new System.Drawing.Point(16, 200);
this.richTextBox1.Name = "richTextBox1 ";
this.richTextBox1.ReadOnly = true;
this.richTextBox1.Size = new System.Drawing.Size(256, 112);
this.richTextBox1.TabIndex = 5;
this.richTextBox1.Text = " ";
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 319);
this.statusBar1.Name = "statusBar1 ";
this.statusBar1.Size = new System.Drawing.Size(288, 22);
this.statusBar1.TabIndex = 6;
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 40);


this.label1.Name = "label1 ";
this.label1.Size = new System.Drawing.Size(100, 24);
this.label1.TabIndex = 7;
this.label1.Text = "目标计算机地址: ";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 168);
this.label2.Name = "label2 ";
this.label2.Size = new System.Drawing.Size(48, 24);
this.label2.TabIndex = 8;
this.label2.Text = "昵称: ";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// textBox3
//
this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.textBox3.ForeColor = System.Drawing.Color.Firebrick;
this.textBox3.Location = new System.Drawing.Point(80, 168);
this.textBox3.Name = "textBox3 ";
this.textBox3.Size = new System.Drawing.Size(72, 21);
this.textBox3.TabIndex = 9;
this.textBox3.Text = " ";

[解决办法]
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(288, 341);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox3,
this.label2,
this.label1,
this.statusBar1,
this.richTextBox1,
this.textBox2,
this.textBox1,
this.button3,
this.button2,
this.button1});
this.Name = "Form1 ";
this.Text = "P2P聊天工具 ";
this.ResumeLayout(false);

}
#endregion

private void Listen()
{
try
{
tcpl = new TcpListener(5656);
tcpl.Start();
statusBar1.Text = "正在监听... ";

while(listenerRun)
{
Socket s = tcpl.AcceptSocket();
Byte[] stream = new Byte[80];
int i=s.Receive(stream) ;
string message = System.Text.Encoding.UTF8.GetString(stream);
richTextBox1.AppendText(message);
}
}
catch(System.Security.SecurityException)
{
MessageBox.Show( "防火墙安全错误! ", "错误 ",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch(Exception)
{
statusBar1.Text = "已停止监听! ";
}
}

private void Send()
{
try
{
string msg = " < "+textBox3.Text+ "> "+textBox2.Text;
TcpClient tcpc = new TcpClient(textBox1.Text, 5656);
NetworkStream tcpStream = tcpc.GetStream();

StreamWriter reqStreamW = new StreamWriter(tcpStream);
reqStreamW.Write(msg);
reqStreamW.Flush();
tcpStream.Close();
tcpc.Close();
richTextBox1.AppendText(msg);
textBox2.Clear();
}
catch(Exception)
{
statusBar1.Text = "目标计算机拒绝连接请求! ";
}
}

private void Stop()
{
tcpl.Stop();
th.Abort();
}


/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
th = new Thread(new ThreadStart(Listen));
th.Start();
}

private void button2_Click(object sender, System.EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
listenerRun = false;
Stop();
}

private void button3_Click(object sender, System.EventArgs e)
{
Send();
}
}
}

读书人网 >C#

热点推荐