本通訊程序沒有服務端和客戶端之分,局域網的計算機運行同一程序即可通信。
由於水平有限,目前版本還很菜,只可以實現基本的聊天功能和顯示在線用戶功能。
准備添加傳送文件、聊天日志、可選參數等功能。
using System;
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.Text;
using System.Threading;
namespace myQQ
{
/// <summary>
/// Form1 的摘要說明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
public bool runing=false; //標志
public UdpClient listen=new UdpClIEnt(2525);
public IPEndPoint End;
public IPAddress groupAddress=IPAddress.Parse("255.255.255.255"); //廣播地址
public int groupPort=2525; //廣播端口
public string MachineName;
public string MachineIP;
public string romeName;
public string romeIP;
public string romeCon;
private System.Windows.Forms.ListBox box;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox t_rec;
private System.Windows.Forms.TextBox t_send;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button newmsg;
/// <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 窗體設計器生成的代碼
/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.box = new System.Windows.Forms.ListBox();
this.t_rec = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.t_send = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.newmsg = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// box
//
this.box.ItemHeight = 12;
this.box.Location = new System.Drawing.Point(0, 32);
this.box.Name = "box";
this.box.Size = new System.Drawing.Size(200, 352);
this.box.TabIndex = 0;
//
// t_rec
//
this.t_rec.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.t_rec.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));
this.t_rec.Location = new System.Drawing.Point(208, 56);
this.t_rec.Multiline = true;
this.t_rec.Name = "t_rec";
this.t_rec.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.t_rec.Size = new System.Drawing.Size(328, 136);
this.t_rec.TabIndex = 1;
this.t_rec.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(208, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(120, 16);
this.label1.TabIndex = 2;
this.label1.Text = "接收:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(208, 200);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 16);
this.label2.TabIndex = 2;
this.label2.Text = "發送:";
//
// t_send
//
this.t_send.Location = new System.Drawing.Point(208, 216);
this.t_send.Multiline = true;
this.t_send.Name = "t_send";
this.t_send.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.t_send.Size = new System.Drawing.Size(328, 112);
this.t_send.TabIndex = 1;
this.t_send.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(440, 344);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 32);
this.button1.TabIndex = 3;
this.button1.Text = "發 送";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button3
//
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.button3.Location = new System.Drawing.Point(88, 3);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(56, 23);
this.button3.TabIndex = 4;
this.button3.Text = "刷 新";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// label3
//
this.label3.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.label3.ForeColor = System.Drawing.Color.Blue;
this.label3.Location = new System.Drawing.Point(8, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 16);
this.label3.TabIndex = 5;
this.label3.Text = "在線用戶:";
//
// button2
//
this.button2.Location = new System.Drawing.Point(360, 344);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 32);
this.button2.TabIndex = 6;
this.button2.Text = "清 空";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// newmsg
//
this.newmsg.Location = new System.Drawing.Point(208, 56);
this.newmsg.Name = "newmsg";
this.newmsg.Size = new System.Drawing.Size(328, 136);
this.newmsg.TabIndex = 7;
this.newmsg.Text = "有新消息了!";
this.newmsg.Click += new System.EventHandler(this.newmsg_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClIEntSize = new System.Drawing.Size(544, 389);
this.Controls.Add(this.button2);
this.Controls.Add(this.label3);
this.Controls.Add(this.button3);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Controls.Add(this.box);
this.Controls.Add(this.label2);
this.Controls.Add(this.t_send);
this.Controls.Add(this.t_rec);
this.Controls.Add(this.newmsg);
this.Name = "Form1";
this.Text = "小y";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
End=new IPEndPoint(groupAddress,groupPort);
//初始化計算機名和端口
IPHostEntry myentry=Dns.GetHostByName(Dns.GetHostName());
IPAddress myaddress=new IPAddress(myentry.AddressList[0].Address);
MachineName=Dns.GetHostName();
MachineIP=myaddress.ToString();
box.Items.Add("IP 主機名");
//開啟監聽線程
runing=true;
Thread myThread=new Thread(new ThreadStart(this.ListenPort));
myThread.Start();
//發送上線信息
string sends="0&"+machineIP+"&"+machineName+"&"+MachineIP;
SendPack(sends);
}
//偵聽指定端口的廣播地址UDP包
public void ListenPort()
{
IPEndPoint tempEnd=new IPEndPoint(IPAddress.Any,2525);
while(runing)
{
Application.DoEvents();
try
{
byte[] recb=listen.Receive(ref tempEnd);
// 檢查所接收到的信息
checkMessage(recb);
}
catch(Exception e)
{
MessageBox.Show(e.Message.ToString());
break;
}
}
listen.Close();
box.Items.Add("線程已經退出!");
runing=false;
}
//循環接收包
public void checkMessage(byte[] recbb)
{
string recStr=Encoding.Default.GetString(recbb);
string[] rec=recStr.Split('&');
switch(rec[0])
{
case "0": //刷新
if(rec[3]==MachineIP)
{
if(box.FindString(rec[1]+" "+rec[2])<=0)
box.Items.Add(rec[1]+" "+rec[2]);
}
else if(rec[1]==rec[3])
{
//從其他機器發送過來的刷新請求
//返回自己的信息
string sendstr="0&"+machineIP+"&"+MachineName+"&"+rec[3];
this.SendPack(sendstr);
//如果不存在則添加該用戶
if(box.FindString(rec[1]+" "+rec[2])<=0)
box.Items.Add(rec[1]+" "+rec[2]);
}
break;
case "1": //發言
if(rec[3]==MachineIP)
{
romeName=rec[2];
romeIP=rec[1];
romeCon=rec[4];
showNe();
}
break;
case "2": //傳文件
break;
case "9": //確認包
if(rec[3]==MachineIP)
MessageBox.Show("信息來自:rec[2]("+rec[1]+")\r\n"+rec[4],"消息");
break;
}
}
//發送數據包到廣播地址
public void SendPack(string sendStr)
{
byte[] sendb=Encoding.Default.GetBytes(sendStr);
try
{
listen.Send(sendb,sendb.Length,End);
}
catch(Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
//刷新
private void button3_Click(object sender, System.EventArgs e)
{
box.Items.Clear();
box.Items.Add("IP 主機名");
string temp2="0&"+machineIP+"&"+machineName+"&"+MachineIP;
this.SendPack(temp2);
}
//關閉循環
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
runing=false;
UdpClient mm=new UdpClIEnt();
IPEndPoint tempIPEnd=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2525);
string temps="0&0&0&0&0";
byte[] sendb=Encoding.Default.GetBytes(temps);
mm.Send(sendb,sendb.Length,tempIPEnd);
}
//發送
private void button1_Click(object sender, System.EventArgs e)
{
if(t_send.Text==null)
{
MessageBox.Show("不能發送空信息!");
return;
}
if(box.SelectedItem==null||box.SelectedIndex==0)
{
MessageBox.Show("請先選擇一個用戶!");
return;
}
string send="1&"+machineIP+"&"+MachineName+"&"+box.SelectedItem.ToString().Split(' ')[0]+"&"+t_send.Text;
this.SendPack(send);
}
//清空
private void button2_Click(object sender, System.EventArgs e)
{
t_send.Text=string.Empty;
t_rec.Text=string.Empty;
}
//單擊顯示接收的信息並隱藏自身
private void newmsg_Click(object sender, System.EventArgs e)
{
t_rec.Text="消息來自"+romeName+"("+romeIP+")"+DateTime.Now.ToShortDateString();
t_rec.Text+="\r\n> "+romeCon;
string back="9&"+machineIP+"&"+MachineName+"&"+romeIP+"&信息被打開!";
this.SendPack(back);
newmsg.SendToBack();
}
//當有信息時顯示提示按鈕
public void showNe()
{
//窗體顯示
if(this.WindowState!=FormWindowstate.Normal)
{
this.Visible=true;
this.WindowState=FormWindowstate.Normal;
}
newmsg.BringToFront();
}
}
}