我给个例子你吧!
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;namespace ChatServer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class ChatServer : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private int listenport = 5555;
private TcpListener listener;
private System.Windows.Forms.ListBox lbClients;
private ArrayList clients;
private Thread processor;
private Socket clientsocket;
private Thread clientservice; public ChatServer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
clients = new ArrayList();
processor = new Thread(new ThreadStart(StartListening));
processor.Start();
} /// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbClients = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lbClients
//
this.lbClients.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lbClients.ItemHeight = 16;
this.lbClients.Location = new System.Drawing.Point(16, 8);
this.lbClients.Name = "lbClients";
this.lbClients.Size = new System.Drawing.Size(264, 228);
this.lbClients.TabIndex = 0;
//
// ChatServer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lbClients});
this.Name = "ChatServer";
this.Text = "ChatServer";
this.ResumeLayout(false); }
#endregion
protected override void OnClosed(EventArgs e)
{
try
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, "QUIT|");
cl.Sock.Close();
cl.CLThread.Abort();
}
listener.Stop();
if(processor != null)
processor.Abort();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString() );
}
base.OnClosed(e);
}
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
private void ServiceClient()
{
Socket client = clientsocket;
bool keepalive = true; while (keepalive)
{
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer); string[] tokens = clientcommand.Split(new Char[]{'|'});
Console.WriteLine(clientcommand); if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens[1]);
}
EndPoint ep = client.RemoteEndPoint;
//string add = ep.ToString();
Client c = new Client(tokens[1], ep, clientservice, client);
clients.Add(c);
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message); //lbClients.Items.Add(c.Name + " : " + c.Host.ToString());
lbClients.Items.Add(c);
}
if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "PRIV") {
string destclient = tokens[3];
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens[3]) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<c; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}
private void SendToClient(Client cl, string message)
{
try{
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message.ToCharArray());
cl.Sock.Send(buffer,buffer.Length,0);
}
catch(Exception e){
cl.Sock.Close();
cl.CLThread.Abort();
clients.Remove(cl);
lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
//MessageBox.Show("Could not reach " + cl.Name + " - disconnected","Error",
//MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private string GetChatterList()
{
string chatters = "";
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
chatters += cl.Name;
chatters += "|";
}
chatters.Trim(new char[]{'|'});
return chatters;
} /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ChatServer());
}
}
}
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;namespace ChatServer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class ChatServer : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private int listenport = 5555;
private TcpListener listener;
private System.Windows.Forms.ListBox lbClients;
private ArrayList clients;
private Thread processor;
private Socket clientsocket;
private Thread clientservice; public ChatServer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
clients = new ArrayList();
processor = new Thread(new ThreadStart(StartListening));
processor.Start();
} /// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbClients = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lbClients
//
this.lbClients.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lbClients.ItemHeight = 16;
this.lbClients.Location = new System.Drawing.Point(16, 8);
this.lbClients.Name = "lbClients";
this.lbClients.Size = new System.Drawing.Size(264, 228);
this.lbClients.TabIndex = 0;
//
// ChatServer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lbClients});
this.Name = "ChatServer";
this.Text = "ChatServer";
this.ResumeLayout(false); }
#endregion
protected override void OnClosed(EventArgs e)
{
try
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, "QUIT|");
cl.Sock.Close();
cl.CLThread.Abort();
}
listener.Stop();
if(processor != null)
processor.Abort();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString() );
}
base.OnClosed(e);
}
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
private void ServiceClient()
{
Socket client = clientsocket;
bool keepalive = true; while (keepalive)
{
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer); string[] tokens = clientcommand.Split(new Char[]{'|'});
Console.WriteLine(clientcommand); if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens[1]);
}
EndPoint ep = client.RemoteEndPoint;
//string add = ep.ToString();
Client c = new Client(tokens[1], ep, clientservice, client);
clients.Add(c);
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message); //lbClients.Items.Add(c.Name + " : " + c.Host.ToString());
lbClients.Items.Add(c);
}
if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "PRIV") {
string destclient = tokens[3];
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens[3]) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
SendToClient(cl, clientcommand);
}
}
if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<c; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}
private void SendToClient(Client cl, string message)
{
try{
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message.ToCharArray());
cl.Sock.Send(buffer,buffer.Length,0);
}
catch(Exception e){
cl.Sock.Close();
cl.CLThread.Abort();
clients.Remove(cl);
lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
//MessageBox.Show("Could not reach " + cl.Name + " - disconnected","Error",
//MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private string GetChatterList()
{
string chatters = "";
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
chatters += cl.Name;
chatters += "|";
}
chatters.Trim(new char[]{'|'});
return chatters;
} /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ChatServer());
}
}
}
public static void Main()
{
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
TcpListener server = new TcpListener(localAddr, port); // Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null; // Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing
NetworkStream stream = client.GetStream(); Int32 i; // Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
// Process the data sent by the client.
data = data.ToUpper(); Byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sent: {0}", data));
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}建议用Windows Service做一个监听服务
//开始服务//************************************************
private void button1_Click(object sender, System.EventArgs e)
{
try
{
if (serverthread!=null)
{ //先要停止原来服务线程
serverthread.Abort();
Thread.Sleep(TimeSpan.FromMilliseconds(400d));
}
//建立一个Tcp服务,端口值在 textBox1.Text
TcpListener tcpserver=new TcpListener( int.Parse(textBox1.Text));
//Tcp服务线程化,ThreadServerProcessor 构造函数的参数可以简化,
serverthread=new ThreadServerProcessor(tcpserver,this.listBox1,this.textBox2.Text,this.textBox3.Text,this.textBox4.Text);
serverthread.StartServer();
}
catch(Exception x)
{
this.listBox1.Items.Add(x.Message);
}
}
//停止服务//****************************************************
private void button2_Click(object sender, System.EventArgs e)
{
if (serverthread!=null)
if(!serverthread.Stop)serverthread.Abort();
Thread.Sleep(TimeSpan.FromMilliseconds(400d));
serverthread=null;
}//
//启动//***********************************************************
private void Form1_Load(object sender, System.EventArgs e)
{
try
{ //取主机名
string host=Dns.GetHostName();
//解析本地IP地址,
IPHostEntry hostIp=Dns.GetHostByName(host);
listBox1.Items.Clear();
listBox1.Items.Add(string.Format("服务器: {0}",host));
//可能是多IP地址
for(int i=0; i<hostIp.AddressList.Length;i++)
listBox1.Items.Add(string.Format("服务器地址 {0},{1} ",i,hostIp.AddressList[i].ToString() ));
}
catch(Exception x)
{ //如果这个时候都出错,就别想活了 ,还是退出
if (MessageBox.Show(this,string.Format("错误:\n {0} \n\n 是否退出?",x.Message),"初始化错误",MessageBoxButtons.YesNo,MessageBoxIcon.Error)==DialogResult.Yes)
Application.Exit();
} //Form1_Load结束!!!!!!!!!!!
} private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (serverthread!=null)
if(!serverthread.Stop)serverthread.Abort();
Thread.Sleep(TimeSpan.FromMilliseconds(400d));
serverthread=null;
}
}//类form1结束////////////////////////////////////////////
/// <summary>
/// ThreadServerProcessor 是服务器端的服务线程类
/// </summary>
public class ThreadServerProcessor
{
//Tcp服务
private System.Net.Sockets.TcpListener tcpListener;
//listBox指向一个外边的消息框
private System.Windows.Forms.ListBox MessageList;
//登陆该服务需要的密码(没有用户名 嬉)
private string Password;
//响应用户命令 "Cmd1" "Cmd2" 应该反会的字符串
private string Cmd1Echo;
private string Cmd2Echo;
//内部线程,指向:void start() 函数
private System.Threading.Thread ServerThread;
//停止服务标志
public bool Stop;
//中断服务
public ThreadServerProcessor(){}
//构造函数,参数解释:Tcp服务,消息框,该服务密码(password命令后的参数) ,命令回应串 1,2
public ThreadServerProcessor(TcpListener tcplistener,ListBox listBox,string LogonText ,string cmd1echo,string cmd2echo)
{
this.tcpListener=tcplistener;
Stop=false;
this.Cmd1Echo=cmd1echo;
this.Cmd2Echo=cmd2echo;
this.MessageList=listBox;
this.Password=LogonText;
}
//启动该服务线程//************************************************************
public void StartServer()
{
if (this.ServerThread!=null)
{
this.MessageList.Items.Add ("线程已经运行......");
return;
}
this.MessageList.Items.Add(string.Format("New TcpListener....Port={0}",this.tcpListener.LocalEndpoint.ToString()));
tcpListener.Start();
//生成线程,start()函数为线程运行时候的程序块
this.ServerThread=new Thread(new ThreadStart(start));
//线程的优先级别
this.ServerThread.Priority=ThreadPriority.BelowNormal;
this.ServerThread.Start();
}
//结束该服务线程,同时要结束由该服务线程所生成的客户连接//********************************
public void Abort()
{
this.MessageList.Items.Add("真在关闭所有客户连接......");
//调用客户线程的静态方法,结束所以生成的客户线程
ThreadClientProcessor.AbortAllClient();
this.MessageList.Items.Add(string.Format("关闭服务线程:{0}",this.tcpListener.LocalEndpoint.ToString()));
this.Stop=true;
//结束本服务启动的线程
if (this.ServerThread!=null) ServerThread.Abort();
tcpListener.Stop();
//程序等500毫秒
Thread.Sleep(TimeSpan.FromMilliseconds(500d));
}
private void start()
{
try
{
while (!Stop) //几乎是死循环
{
this.MessageList.Items.Add("等待客户机连接......");
//等待Tcp客户端连接,生成Tcp客户端,这个时候,线程处于阻塞状态
TcpClient tcpclient=tcpListener.AcceptTcpClient();
this.MessageList.Items.Add("建立了一个客户连接......");
//给客户端连接另外启动一个读写线程,ThreadClientProcessor 在后续
ThreadClientProcessor tcpthread=new ThreadClientProcessor(tcpclient,this.MessageList,this.Password,this.Cmd1Echo,this.Cmd2Echo);
tcpthread.Start();
if (Stop) break;
}
}
finally
{
this.tcpListener.Stop();
}
}
}// ThreadServerProcessor 结束
/// Tcp客户线程类(服务端),ThreadServerProcessor 线程产生的客户连接,用该线程读写
/// </summary>
public class ThreadClientProcessor
{
//Tcp连接实例
private TcpClient tcpClient;
//消息框,本来想写日志用
private System.Windows.Forms.ListBox MessageList;
private string Password; //该连接登陆密码
private string Cmd1Echo;
private string Cmd2Echo;
private bool ClientLogOn;//客户是否登陆
private bool TcpClose;
public ThreadClientProcessor(){}
//构造函数,参数解释:Tcp客户,消息框,该服务密码(password命令后的参数) ,命令回应串 1,2 ******************
public ThreadClientProcessor(TcpClient client , ListBox listBox,string LogonText ,string cmd1echo,string cmd2echo)
{
ClientList.Add(this); //把当前实例加入一个列表中,方便以后控制
this.tcpClient=client;
this.MessageList=listBox;
this.Password=LogonText;
this.Cmd1Echo=cmd1echo;
this.Cmd2Echo=cmd2echo;
this.ClientLogOn=false;
this.TcpClose=false;
}
public static char[] CmdSplit={' '}; //读来的串由' ' 进行分离,命名+' '+参数
//public const string[] Cmd=new string[] { "password","cmd1","cmd2","echo","bye"};
//该函数由你自己写,这个只是给一个例子,
//功能:命令处理器,给个命令串,返回该命令处理结果,把命令和处理结果放在一个文本文件里,便于系统升级
public string TcpCmd(string s)
{
string result;
try
{
string cmdarg=s.Trim();
string[] args=cmdarg.Split(CmdSplit);
string cmd=args[0].ToLower();
switch (cmd )
{
case "password" :
if (args.Length>1)
{
ClientLogOn= Password.Equals(args[1].Trim());
result=ClientLogOn? "登陆成功":"密码不正确,未登陆";
}
else result= "登陆时候,没有输入密码";
break;
case "cmd1":
result=ClientLogOn?this.Cmd1Echo:"该命令无权执行,请先登陆";
break;
case "cmd2":
result=ClientLogOn?this.Cmd2Echo:"该命令无权执行,请先登陆";
break;
case "echo":
result=string.Format("服务器回应:\n {0}",s);
break;
case "bye":
this.TcpClose=true;
result="DisConnected";
break;
default:
result="不可识别的命令";
break;
}
}
catch
{
result="解析命令发生错误,你输入的是狗屁命令,TMD *^* ";
}
return result;
} //end cmd
//定义一个线程,该线程对应的函数是 void start()(不是Start())********************************
//一下程序主要是操作该线程
public System.Threading.Thread tcpClientThread;
//启动客户连接线程 *************************************************************
public void Start()
{
tcpClientThread=new Thread(new ThreadStart(start));
tcpClientThread.Priority=ThreadPriority.BelowNormal;
tcpClientThread.Start();
}
//断开该当前实例连接,终止线程 **************************************************************
public void Abort()
{
if (this.tcpClientThread!=null)
{
//tcpClientThread.Interrupt();
tcpClientThread.Abort();
//一定要等一会儿,以为后边tcpClient.Close()时候,会影响NetWorkStream的操作
Thread.Sleep(TimeSpan.FromMilliseconds(100));
tcpClient.Close();
}
}
//静态列表,包含了每个连接实例(在构造实例时候使用了 ArrayList.Add( object))
private static System.Collections.ArrayList ClientList=new ArrayList();
//断开所有的Tcp客户连接,静态方法*************************************************************
public static void AbortAllClient()
{
for(int j=0 ;j< ClientList.Count;j++)
{
//从实例列表中取一个对象,转化为ThreadClientProcessor对象
ThreadClientProcessor o=(ThreadClientProcessor ) ClientList[j];
//调用ThreadClientProcessor 对象的停止方法
o.Abort();
}
//清除连接列表
ClientList.Clear();
}
//读写连接的函数,用于线程//*******************************************************************
private void start()
{
byte[] buf=new byte[1024*1024]; //预先定义1MB的缓冲
int Len=0; //流的实际长度
NetworkStream networkStream=tcpClient.GetStream(); //建立读写Tcp的流
try
{
byte[] p=Encoding.UTF8.GetBytes(" 欢迎光临,请输入密码" );
//向Tcp连接写 欢迎消息
if (!this.ClientLogOn )
networkStream.Write(p,0,p.Length);
//开始循环读写tcp流
while (!TcpClose)
{
//如果当前线程是在其它状态,(等待挂起,等待终止.....)就结束该循环
if (Thread.CurrentThread.ThreadState!=ThreadState.Running)
break;
//判断Tcp流是否有可读的东西
if ( networkStream.DataAvailable)
{
//从流中读取缓冲字节数组
Len=networkStream.Read(buf,0,buf.Length);
//转化缓冲数组为串
string cmd=Encoding.UTF8.GetString(buf,0,Len);
this.MessageList.Items.Add("客户机:"+cmd);
//处理该缓冲的串(分析命令),分析结果为res串
string res=TcpCmd(cmd);
//把命令的返回结果res 转化为字节数组
byte[] result=Encoding.UTF8.GetBytes(res);
//发送结果缓冲数组给客户端
networkStream.Write(result,0,result.Length);
this.MessageList.Items.Add("服务器回应:"+res);
}
else
{
//Thread.Sleep(TimeSpan.FromMilliseconds(200d));
//this.MessageList.Items.Add("客户机无命令");
//如果当前Tcp连接空闲,客户端没有写入,则当前线程停止200毫秒
Thread.Sleep(TimeSpan.FromMilliseconds(200d));
}
}
正在实验传送XML数据流的操作,有问题还会来请教各位。
正在实验传送XML数据流的操作,有问题还会来请教各位。
正在实验传送XML数据流的操作,有问题还会来请教各位。