using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Text; using System.Net.Sockets; using System.Threading; namespace 通信 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class FrmMessageBox : System.Windows.Forms.Form { private System.Windows.Forms.ListBox ListHim; private System.Windows.Forms.Button ButOk; private System.Windows.Forms.TextBox TxtIp;
以下是服务器端代码片段private void btn_UdpServer_Click(object sender, System.EventArgs e)
{
Thread bThread = new Thread(new ThreadStart(backThread));
bThread.Start();
} private void backThread()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,12345);
localSocket = new UdpClientNew(ipep); while (true)
{
IPEndPoint remote = new IPEndPoint(IPAddress.Any,0);;
data = localSocket.Receive(ref remote);
MessageBox.Show("远程地址:"+remote.Address.ToString()+" 端口:"+remote.Port.ToString());
ThreadContainer tc = new ThreadContainer(localSocket,remote,data);
Thread newThread = new Thread(new ThreadStart(tc.ManageThread));
newThread.Start();
}
MessageBox.Show("玩完!");
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
localSocket.Close();
}
} public class ThreadContainer
{
private UdpClientNew localSocket;
private IPEndPoint remote;
private byte[] data; public ThreadContainer(UdpClientNew localSocket,IPEndPoint remote,byte[] data)
{
this.localSocket = localSocket;
this.remote = remote;
this.data = data;
}
public void ManageThread()
{
MsgManage mm = new MsgManage(localSocket,data,remote);
mm.DisposalMsg();
//rtb_MsgList.Text += "完成一次数据交换\n";
}
}
mm.DisposalMsg();查看一下问题是否出在这!
参考一下吧。
private Thread startListen;
this.startListen = new Thread(new ThreadStart(this.hostListenStart));ipep = new IPEndPoint(IPAddress.Any, Int32.Parse(this.tbPort.Text));//tbPort端口号
hostSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
hostSocket.Bind(ipep);
hostSocket.Listen(10);
this.startListen.Start();private void hostListenStart()
{
while(true)
{
hostSocket.BeginAccept(new AsyncCallback(CallAccept), hostSocket);
Thread.Sleep(100);
}
}
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace 通信
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class FrmMessageBox : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox ListHim;
private System.Windows.Forms.Button ButOk;
private System.Windows.Forms.TextBox TxtIp;
private System.Net.IPAddress locaip=Dns.GetHostByName(Dns.GetHostName()).AddressList[0]; //本机IP地址
private System.Windows.Forms.TextBox TxtMe;
private Thread thread;
private System.Windows.Forms.Button ButCn;
private System.Windows.Forms.Label label1;
private System.Net.Sockets.UdpClient udpclientreceive=null;
private bool closebool=false;
private System.Windows.Forms.Label label2;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public FrmMessageBox()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.TxtMe = new System.Windows.Forms.TextBox();
this.ListHim = new System.Windows.Forms.ListBox();
this.ButOk = new System.Windows.Forms.Button();
this.TxtIp = new System.Windows.Forms.TextBox();
this.ButCn = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// TxtMe
//
this.TxtMe.Location = new System.Drawing.Point(0, 200);
this.TxtMe.Multiline = true;
this.TxtMe.Name = "TxtMe";
this.TxtMe.Size = new System.Drawing.Size(496, 112);
this.TxtMe.TabIndex = 0;
this.TxtMe.Text = "";
//
// ListHim
//
this.ListHim.HorizontalScrollbar = true;
this.ListHim.ItemHeight = 12;
this.ListHim.Location = new System.Drawing.Point(0, 25);
this.ListHim.Name = "ListHim";
this.ListHim.Size = new System.Drawing.Size(496, 160);
this.ListHim.TabIndex = 1;
//
// ButOk
//
this.ButOk.Location = new System.Drawing.Point(336, 320);
this.ButOk.Name = "ButOk";
this.ButOk.TabIndex = 2;
this.ButOk.Text = "发送(&O)";
this.ButOk.Click += new System.EventHandler(this.ButOk_Click);
//
// TxtIp
//
this.TxtIp.Location = new System.Drawing.Point(48, 318);
this.TxtIp.Name = "TxtIp";
this.TxtIp.Size = new System.Drawing.Size(144, 21);
this.TxtIp.TabIndex = 3;
this.TxtIp.Text = "192.168.1.141";
//
// ButCn
//
this.ButCn.Location = new System.Drawing.Point(424, 320);
this.ButCn.Name = "ButCn";
this.ButCn.TabIndex = 4;
this.ButCn.Text = "关闭(&C)";
this.ButCn.Click += new System.EventHandler(this.ButCn_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(0, 320);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 17);
this.label1.TabIndex = 5;
this.label1.Text = "对方IP:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(1, 3);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(60, 17);
this.label2.TabIndex = 6;
this.label2.Text = "聊天记录:";
//
// FrmMessageBox
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(512, 349);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.ButCn);
this.Controls.Add(this.TxtIp);
this.Controls.Add(this.ButOk);
this.Controls.Add(this.ListHim);
this.Controls.Add(this.TxtMe);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "FrmMessageBox";
this.Text = "聊天工具";
this.Closing += new System.ComponentModel.CancelEventHandler(this.FrmMessageBox_Closing);
this.Load += new System.EventHandler(this.FrmMessageBox_Load);
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new FrmMessageBox());
} public void sRead()
{
Thread.Sleep(0);
System.Net.IPEndPoint locaipport=new IPEndPoint(locaip,1111);
udpclientreceive =new UdpClient(locaipport);
while(true)
{
string ReadString=Encoding.UTF8.GetString(udpclientreceive.Receive(ref locaipport)); //接收数据
if(ReadString.Length>0)
{
int idx=this.ListHim.Items.Add(ReadString);
this.ListHim.SelectedIndex=idx;
}
if(closebool==true)
{
udpclientreceive.Close();
break;
}
}
} private void FrmMessageBox_Load(object sender, System.EventArgs e)
{
//启动接收数据的线程
thread =new Thread(new ThreadStart(sRead));
thread.Start();
} private void ButOk_Click(object sender, System.EventArgs e)
{
string sendstring="";
if(this.TxtMe.Text.Trim().Length>0)
{
if(locaip.ToString()!=this.TxtIp.Text.Trim())
{
sendstring=locaip.ToString()+"对"+this.TxtIp.Text.Trim()+"说:"+TxtMe.Text.Trim();
int idx=this.ListHim.Items.Add(sendstring);
this.ListHim.SelectedIndex=idx;
}
else
sendstring=locaip.ToString()+"对自已说:"+TxtMe.Text.Trim();
udpsend(this.TxtIp.Text.Trim(),sendstring);
this.TxtMe.Text="";
}
else
{
MessageBox.Show("发送信息不能为空","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
this.TxtMe.Focus();
} private void ButCn_Click(object sender, System.EventArgs e)
{
this.Close();
} private void FrmMessageBox_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
closebool=true;
udpsend(locaip.ToString(),"");
}
/// <summary>
/// 用UDP发送信息
/// </summary>
/// <param name="ReceiveIp">收信息的主机IP</param>
/// <param name="SendString">要发送的内容</param>
private void udpsend(string ReceiveIp,string SendString)
{
System.Net.IPEndPoint locaipport=new IPEndPoint(System.Net.IPAddress.Parse(ReceiveIp),1111);
System.Net.Sockets.UdpClient udpclient =new UdpClient();
byte[] bytes =Encoding.UTF8.GetBytes(SendString);
udpclient.Send(bytes,bytes.Length,locaipport);
}
}
}