如果网络规模不大,是不是可以考虑用广播 发送: Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast,9050); byte[] data = Encoding.ASCII.GetBytes(id); sock.SendTo(data,iep); sock.Close(); 这个在你按按钮的时候执行.接收: Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any,9050); sock.Bind(iep); EndPoint ep = (EndPoint)iep; byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data,ref ep); string id = Encoding.ASCII.GetString(data,0,recv); MessageBox.Show(id); sock.Close();
发送:
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast,9050);
byte[] data = Encoding.ASCII.GetBytes(id);
sock.SendTo(data,iep);
sock.Close();
这个在你按按钮的时候执行.接收:
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any,9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data,ref ep);
string id = Encoding.ASCII.GetString(data,0,recv);
MessageBox.Show(id);
sock.Close();
做一个server和一个client,server运行后对一个端口进行监听,client登录后与server建立连接,当client想发消息时,就构建一条命令发给server,如:MODI|SENDER|RECIVER|ORDERID,基中,MODI是告诉server进行的定单修改操作,SENDER是告诉server发送消息的人是谁,RECIVER是告诉server这个消息是发给谁的,ORDERID是告诉server所修改的定单号是多少.server收到这条消息后,进行解析,然后根据解析决定发给谁,所发送的消息可以与MODI|SENDER|RECIVER|ORDERID相同.当另一client收到这条消息后,就对这条消息进行解析,就可以了解到这条消息是谁发来的,表示的是什么意思,等等
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.Threading;
using System.Text;
using System.IO;
namespace chatServer
{
/// <summary>
/// ChatServerForm 的摘要说明。
/// </summary>
public class ChatServerForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtHost;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox CurUserList;
private System.Windows.Forms.ListBox lstInfo;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
static int port=1234;
private TcpListener listener;
private Socket tmpSocket;
static int MaxNum=100;
static ArrayList clients=new ArrayList(); public ChatServerForm()
{
//
// 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.label1 = new System.Windows.Forms.Label();
this.txtHost = new System.Windows.Forms.TextBox();
this.btnStart = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.txtPort = new System.Windows.Forms.TextBox();
this.btnExit = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.CurUserList = new System.Windows.Forms.ComboBox();
this.lstInfo = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 0;
this.label1.Text = "主机号:";
//
// txtHost
//
this.txtHost.Location = new System.Drawing.Point(128, 32);
this.txtHost.Name = "txtHost";
this.txtHost.Size = new System.Drawing.Size(96, 21);
this.txtHost.TabIndex = 1;
this.txtHost.Text = "192.168.100.9";
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(280, 32);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(80, 24);
this.btnStart.TabIndex = 2;
this.btnStart.Text = "启动";
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 80);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 16);
this.label2.TabIndex = 3;
this.label2.Text = "端口号:";
//
// txtPort
//
this.txtPort.Location = new System.Drawing.Point(128, 72);
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(96, 21);
this.txtPort.TabIndex = 4;
this.txtPort.Text = "1234";
//
// btnExit
//
this.btnExit.Location = new System.Drawing.Point(280, 72);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(80, 24);
this.btnExit.TabIndex = 5;
this.btnExit.Text = "退出";
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(24, 128);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(88, 24);
this.label3.TabIndex = 6;
this.label3.Text = "当前在线用户:";
//
// CurUserList
//
this.CurUserList.Location = new System.Drawing.Point(128, 120);
this.CurUserList.Name = "CurUserList";
this.CurUserList.Size = new System.Drawing.Size(96, 20);
this.CurUserList.TabIndex = 7;
this.CurUserList.Text = "comboBox1";
//
// lstInfo
//
this.lstInfo.ItemHeight = 12;
this.lstInfo.Location = new System.Drawing.Point(16, 168);
this.lstInfo.Name = "lstInfo";
this.lstInfo.Size = new System.Drawing.Size(336, 100);
this.lstInfo.TabIndex = 8;
//
// ChatServerForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(384, 273);
this.Controls.Add(this.lstInfo);
this.Controls.Add(this.CurUserList);
this.Controls.Add(this.label3);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.txtPort);
this.Controls.Add(this.label2);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.txtHost);
this.Controls.Add(this.label1);
this.Name = "ChatServerForm";
this.Text = "ChatServerForm";
this.Load += new System.EventHandler(this.ChatServerForm_Load);
this.ResumeLayout(false); }
#endregion
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ChatServerForm());
} private void ChatServerForm_Load(object sender, System.EventArgs e)
{
} private void btnStart_Click(object sender, System.EventArgs e)
{
//txtPort.Text=port.ToString();
// port=(int)txtPort.Text;
//txtPort.Text=port.ToString();
try
{
IPAddress ipAdd=IPAddress.Parse("192.168.100.9");
//txtHost.Text="192.168.100.185";
listener=new TcpListener(ipAdd,port);
listener.Start();
lstInfo.Items.Add("服务器已经启动,正在监听"+txtHost.Text+":"+txtPort.Text);
Thread thread=new Thread(new ThreadStart(this.StartListen));
thread.Start();
btnStart.Enabled=false;
}
catch(Exception ex)
{
lstInfo.Items.Add(ex.Message.ToString());
}
}
private void StartListen()
{
while(true)
{
try
{
Socket socket=listener.AcceptSocket();
tmpSocket=socket;
if(clients.Count>=MaxNum)
{
tmpSocket.Close();
}
else
{
Thread clientService=new Thread(new ThreadStart(this.ServiceClient));
clientService.Start();
}
}
catch(Exception ex)
{
lstInfo.Items.Add(ex.Message.ToString());
}
}
}
private void ServiceClient()
{
byte[] buff=new byte[1024];
Socket clientSocket=tmpSocket;
bool keepConnect=true;
while(keepConnect)
{
clientSocket.Receive(buff);
string clientCommand=System.Text.Encoding.ASCII.GetString(buff); string[] tokens=clientCommand.Split(new Char[]{'|'});
if(tokens[0]=="CONN")
{
Client _client=new Client(tokens[1],clientSocket);
clients.Add(_client);
lstInfo.Items.Add(tokens[1]+" "+"加入了");
CurUserList.Items.Add(tokens[1]);
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
SendToClient(client,"JOIN|"+tokens[1]+"12|");
Thread.Sleep(100);
string msgUsers="LIST|"+GetUserList();
SendToClient(client,msgUsers);
}
}
if(tokens[0]=="CHAT")
{
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
SendToClient(client,tokens[1]);
}
}
if(tokens[0]=="PRIV")
{
string sender=tokens[1];
string receiver=tokens[2];
string content=tokens[3];
string message=sender+" send to "+receiver+": "+content;
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
if(client.Name.CompareTo(tokens[2])==0)
SendToClient(client,message);
if(client.Name.CompareTo(tokens[1])==0)
SendToClient(client,message);
}
}
if(tokens[0]=="EXIT")
{
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
string message=tokens[1]+"has gone!";
SendToClient(client,message);
if(client.Name.CompareTo(tokens[1])==0)
{
clients.RemoveAt(i);
CurUserList.Items.Remove(client.Name);
message="QUIT|";
SendToClient(client,message);
}
}
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
string message="LIST|"+GetUserList();
SendToClient(client,message);
}
lstInfo.Items.Add(tokens[1]+"has gone!");
clientSocket.Close();
keepConnect=false;
}
}
}
private void SendToClient(Client client,string msg)
{
System.Byte[] message=System.Text.Encoding.ASCII.GetBytes(msg.ToCharArray());
client.clientSocket.Send(message,message.Length,0);
}
private string GetUserList()
{
string Rtn="";
for(int i=0;i<clients.Count;i++)
{
Client client=(Client)clients[i];
Rtn=Rtn+client.Name+"|";
}
return Rtn;
} private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private class Client
{
string name;
Socket clSocket;
public Client(string _name,Socket _socket)
{
name=_name;
clSocket=_socket;
}
public string Name
{
get
{
return name;
}
set
{
name=value;
}
}
public Socket clientSocket
{
get
{
return clSocket;
}
set
{
clSocket=value;
}
}
}
}}
的正解