看见还有很多人在研究flash的socket,其中经常会出现一些问题,所以将我以前写的一个程序代码拿出来给大家参考...
这是c#的代码,经过测试的,本来想把源程序都放上来,可以我用的是vs2005(而且现在又坏了,系统出问题了),下面是程序的主要源代码,不包含一些自动生成的代码.这些代码是根据一个开源的C#socket程序改编的,而且我已经写了比较详细的注释了,如果你看了这些代码还是发现有问题,可以向我索取完整的源程序:
把源文件传上来,大家可以下载(gmail又打不开了,不能给留email的同学发了,自己下载吧):
点击下载此文件 //--------------------------------
//--------------------------------------------------------------------------------------------------------------- //form1.cs using System; using System.IO; using System.Drawing; using System.Collections;//ArrayList引用到这个命名空间的类 using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.Threading;
namespace ChatServer//服务器端命名空间 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private int listenport = 9050;//监听端口 private TcpListener listener;//监听者 private ArrayList clients;//所有的client private Thread processor;//处理线程 private Socket clientsocket;//client套接字 private Thread clientservice;//client的服务 private System.Windows.Forms.ListBox lbClients; private System.Windows.Forms.Label label1;//显示在线人员的List控件
private TcpClient tclient;
private NetworkStream ns; private System.Windows.Forms.Button button1;
/// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null;
public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); Thread.CurrentThread.IsBackground = true; // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // clients = new ArrayList();//新建一个ArrayList类型用以存储所有的client processor = new Thread(new ThreadStart(StartListening));//新建一个处理线程 processor.Start();//线程开始 //
}
/// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) {
int c = clients.Count; for(int n=0; n<c; n++) { Client cl = (Client)clients[n]; cl.Sock.Close(); cl.CLThread.Abort(); }
//client.Close(); listener.Stop(); processor.Abort(); if( disposing ) { if (components != null)
{ components.Dispose(); } } base.Dispose( disposing ); }
/// <summary> /// 开始监听 /// </summary> private void StartListening() {
IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0]; //IPAddress ipAddress = IPAddress.Parse("192.168.0.132");
label1.Text=ipAddress.ToString(); IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, listenport);
listener = new TcpListener(ipLocalEndPoint); listener.Start(); while (true) |