using dental
private void StartMsgThread()
{
InitSocket.MessageThread =new Thread(new ThreadStart(ListenToMsg));
InitSocket.MessageThread.IsBackground=true;//线程为后台线程,程序结束后线程自动终止
InitSocket.MessageThread.Start();
}
private void ListenToMsg()
{
try
{
while(InitSocket.RunFlag)
{
string returnData=dental.InitSocket.ReceiveMessage();
if(returnData!="")
{
this.TextReceive.Text +=returnData +"\r\n";
}
if(!dental.InitSocket.RunFlag)//若运行标志变为False,则中止线程
{
dental.InitSocket.AbortMessageT();
}
}
//this.ListenToMsg();
}
catch(Exception ex)
{
this.ShowError(ex.Message+";UDP监听不成功!");
}private void SendMsg()
{
try
{
string UserInfo="<"+dental.AppShare.UserID+":"+dental.AppShare.UserName+">"+
"("+System.DateTime.Now.ToString()+")";
string TalkMesage=this.textMessage.Text;
dental.InitSocket.SendMessage(UserInfo+TalkMesage);
}
catch(Exception ex)
{
this.ShowError(ex.Message+";网络故障,发送请求失败");
}
}
Class InitSocket:
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace dental
{
/// <summary>
/// Summary description for InitSocket.
/// </summary>
public class InitSocket
{
const int READ_BUFFER_SIZE = 255;
const int PORT_NUM = 9002; //定义应用程序端口号
const int SEND_PORT_NUM = 9003;
public enum iPort:int
{
MsgPort=9002,
MailPort=9003
}
public enum IBufferSize:int
{
Small=100,
Normal=255,
Big=1024
}
static private bool boolRunFlag;
static private UdpClient UdpMsgSender;
static private UdpClient UdpMsgReceiver;
static private System.Threading.Thread MsgThread;
static private System.Windows.Forms.Form frmMessage;
static InitSocket()
{
//
// TODO: Add constructor logic here
UdpMsgSender=new UdpClient();
UdpMsgReceiver=new UdpClient(PORT_NUM);
//
} static public bool RunFlag
{
get{return boolRunFlag;}
set{boolRunFlag=value;}
}
#region "消息窗体"
static public System.Windows.Forms.Form FormMessage
{
set{frmMessage=value;}
get{return frmMessage;}
}
#endregion #region "添加、终止应用程序工作线程"
static public Thread MessageThread
{
get{return MsgThread;}
set{MsgThread=value;}
}
static public void AbortMessageT()
{
if(MsgThread!=null)
{
if(!MsgThread.IsBackground)
{
MsgThread.Abort();
MsgThread.Join();
}
}
}
#endregion #region "返回Socket实例"
static public UdpClient MessageSender
{
get{return UdpMsgSender;}
}
static public UdpClient MessageReceiver
{
get{return UdpMsgReceiver;}
}
#endregion #region "关闭Socket连接"
static public void CloseReceiver()
{
UdpMsgReceiver.Close();
}
static public void CloseSender()
{
UdpMsgSender.Close();
}
#endregion #region "发送、接收消息"
static public string ReceiveMessage()
{
IPEndPoint remoteEndPoint=null;
byte[] receivebytes=UdpMsgReceiver.Receive(ref remoteEndPoint);
string returnData=Encoding.GetEncoding("gb2312").GetString(receivebytes);
return returnData;
}
static public void SendMessage(string strSend)
{
IPAddress desAddress=IPAddress.Parse("255.255.255.255");//设置广播地址
UdpMsgSender.Connect(desAddress,PORT_NUM);
byte[] bytes=Encoding.GetEncoding("gb2312").GetBytes(strSend);
UdpMsgSender.Send(bytes,bytes.Length);
}
#endregion
}
}
private void StartMsgThread()
{
InitSocket.MessageThread =new Thread(new ThreadStart(ListenToMsg));
InitSocket.MessageThread.IsBackground=true;//线程为后台线程,程序结束后线程自动终止
InitSocket.MessageThread.Start();
}
private void ListenToMsg()
{
try
{
while(InitSocket.RunFlag)
{
string returnData=dental.InitSocket.ReceiveMessage();
if(returnData!="")
{
this.TextReceive.Text +=returnData +"\r\n";
}
if(!dental.InitSocket.RunFlag)//若运行标志变为False,则中止线程
{
dental.InitSocket.AbortMessageT();
}
}
//this.ListenToMsg();
}
catch(Exception ex)
{
this.ShowError(ex.Message+";UDP监听不成功!");
}private void SendMsg()
{
try
{
string UserInfo="<"+dental.AppShare.UserID+":"+dental.AppShare.UserName+">"+
"("+System.DateTime.Now.ToString()+")";
string TalkMesage=this.textMessage.Text;
dental.InitSocket.SendMessage(UserInfo+TalkMesage);
}
catch(Exception ex)
{
this.ShowError(ex.Message+";网络故障,发送请求失败");
}
}
Class InitSocket:
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace dental
{
/// <summary>
/// Summary description for InitSocket.
/// </summary>
public class InitSocket
{
const int READ_BUFFER_SIZE = 255;
const int PORT_NUM = 9002; //定义应用程序端口号
const int SEND_PORT_NUM = 9003;
public enum iPort:int
{
MsgPort=9002,
MailPort=9003
}
public enum IBufferSize:int
{
Small=100,
Normal=255,
Big=1024
}
static private bool boolRunFlag;
static private UdpClient UdpMsgSender;
static private UdpClient UdpMsgReceiver;
static private System.Threading.Thread MsgThread;
static private System.Windows.Forms.Form frmMessage;
static InitSocket()
{
//
// TODO: Add constructor logic here
UdpMsgSender=new UdpClient();
UdpMsgReceiver=new UdpClient(PORT_NUM);
//
} static public bool RunFlag
{
get{return boolRunFlag;}
set{boolRunFlag=value;}
}
#region "消息窗体"
static public System.Windows.Forms.Form FormMessage
{
set{frmMessage=value;}
get{return frmMessage;}
}
#endregion #region "添加、终止应用程序工作线程"
static public Thread MessageThread
{
get{return MsgThread;}
set{MsgThread=value;}
}
static public void AbortMessageT()
{
if(MsgThread!=null)
{
if(!MsgThread.IsBackground)
{
MsgThread.Abort();
MsgThread.Join();
}
}
}
#endregion #region "返回Socket实例"
static public UdpClient MessageSender
{
get{return UdpMsgSender;}
}
static public UdpClient MessageReceiver
{
get{return UdpMsgReceiver;}
}
#endregion #region "关闭Socket连接"
static public void CloseReceiver()
{
UdpMsgReceiver.Close();
}
static public void CloseSender()
{
UdpMsgSender.Close();
}
#endregion #region "发送、接收消息"
static public string ReceiveMessage()
{
IPEndPoint remoteEndPoint=null;
byte[] receivebytes=UdpMsgReceiver.Receive(ref remoteEndPoint);
string returnData=Encoding.GetEncoding("gb2312").GetString(receivebytes);
return returnData;
}
static public void SendMessage(string strSend)
{
IPAddress desAddress=IPAddress.Parse("255.255.255.255");//设置广播地址
UdpMsgSender.Connect(desAddress,PORT_NUM);
byte[] bytes=Encoding.GetEncoding("gb2312").GetBytes(strSend);
UdpMsgSender.Send(bytes,bytes.Length);
}
#endregion
}
}
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;namespace WindowsApplication1
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.RichTextBox richTextBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private Thread UdpThread;
//pivate UDP Socket;
private Socket udpsocket;
private System.ComponentModel.Container components = null; public Form1()
{
udpsocket=new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
InitializeComponent();
UDPListen();
} 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.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.tabPage1,
this.tabPage2});
this.tabControl1.Location = new System.Drawing.Point(24, 16);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(384, 224);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button1,
this.richTextBox1});
this.tabPage1.Location = new System.Drawing.Point(4, 21);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(376, 199);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "聊天室一";
//
// tabPage2
//
this.tabPage2.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button2,
this.richTextBox2});
this.tabPage2.Location = new System.Drawing.Point(4, 21);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(376, 199);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "聊天室二";
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(32, 24);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(320, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// richTextBox2
//
this.richTextBox2.Location = new System.Drawing.Point(32, 32);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(328, 96);
this.richTextBox2.TabIndex = 0;
this.richTextBox2.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(168, 144);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "发送";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(152, 144);
this.button2.Name = "button2";
this.button2.TabIndex = 1;
this.button2.Text = "发送";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(416, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.tabControl1});
this.Name = "Form1";
this.Text = "Form1";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e)
{
try
{
Byte[] ReadBuffer = Encoding.UTF8.GetBytes(richTextBox1.Text);
IPEndPoint ipep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),5001);//127.0.0.1可以改成对方的IP地址
udpsocket.SendTo(ReadBuffer,ReadBuffer.Length,SocketFlags.None,ipep);
}
catch( Exception err ) { MessageBox.Show(err.Message,"not properly.",MessageBoxButtons.OK, MessageBoxIcon.Error);}
} private void button2_Click(object sender, System.EventArgs e)
{
try
{
Byte[] ReadBuffer = Encoding.UTF8.GetBytes(richTextBox1.Text);
IPEndPoint ipep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),5001);//127.0.0.1可以改成对方的IP地址
udpsocket.SendTo(ReadBuffer,ReadBuffer.Length,SocketFlags.None,ipep);
}
catch( Exception err ) { MessageBox.Show(err.Message,"not properly.",MessageBoxButtons.OK, MessageBoxIcon.Error);}
}
//start to UDP listen
void UDPListen()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 5002);
udpsocket.Bind(ipLocalEndPoint);
UdpThread = new Thread( new ThreadStart(UdpReceiver));
UdpThread.Start();
}
catch( Exception er ) { MessageBox.Show(er.Message,"UDPListen error.",MessageBoxButtons.OK, MessageBoxIcon.Error);} } void UdpReceiver()
{
while(true)
{
// read what the browser wrote through UDP
byte[] read=new byte[1024];
udpsocket.Receive(read);
}
}
}
}
while(InitSocket.RunFlag)
{
dental.InitSocket.ReceiveMessage();
}
但是发送的程序SendMsg()中没有用循环
private void SendMsg()
{
dental.InitSocket.SendMessage(UserInfo+TalkMesage);
}这样不是也只能发送一次吗?
我这又不是完整的代码,这只是一部分(发送和接受的,其他的没贴上来),所以你不必那么激动地说我的代码有问题,当然我的程序是经过测试的,没有问题的。
TO楼主:
发送消息是当用户点击发送按钮后触发事件再调用SendMsg()来实现的,你现在要做什么?
是让机器不断的自动发消息,还是由一定的条件触发后,再发送一条信息?
如果是前者,只要在一个循环体中调用sendMsg就可以了。
由于Udp的多播现在的路由器不支持,我想把一条消息发给用我的聊天程序的各个在线的用户只能挨个发送(已经知道各个用户的IP地址)。不过不是让机器不断的自动发消息,而是按发送按钮后逐个发送。如果您有类似程序请发一份给我,我的email是:[email protected] 多谢!另外请问我想给您100分怎么给?