1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7using System.Text;
  8using System.Net;
  9using System.Net.Sockets;
 10using System.Threading;
 11
 12namespace TServer
 13{
 14    /// <summary>
 15    /// Form1 的摘要说明。
 16    /// </summary>

 17    public class Form1 : System.Windows.Forms.Form
 18    {
 19        private System.Windows.Forms.TextBox txt;
 20        private System.Net.Sockets.Socket server;
 21        private System.Windows.Forms.ComboBox cmbIP;
 22        private System.Windows.Forms.Button btnStart;
 23        private System.Windows.Forms.Button btnStop;
 24        private System.Windows.Forms.StatusBar statBar;
 25        private System.Threading.ManualResetEvent allDone;
 26        private byte[] buffer;
 27        /// <summary>
 28        /// 必需的设计器变量。
 29        /// </summary>

 30        private System.ComponentModel.Container components = null;
 31
 32        public Form1()
 33        {
 34            //
 35            // Windows 窗体设计器支持所必需的
 36            //
 37            InitializeComponent();
 38
 39            //
 40            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 41            //
 42        }

 43
 44        /// <summary>
 45        /// 清理所有正在使用的资源。
 46        /// </summary>

 47        protected override void Dispose( bool disposing )
 48        {
 49            if( disposing )
 50            {
 51                if (components != null
 52                {
 53                    components.Dispose();
 54                }

 55            }

 56            base.Dispose( disposing );
 57        }

 58
 59        Windows 窗体设计器生成的代码
132
133        /// <summary>
134        /// 应用程序的主入口点。
135        /// </summary>

136        [STAThread]
137        static void Main() 
138        {
139            Application.Run(new Form1());
140        }

141
142        private void Form1_Load(object sender, System.EventArgs e)
143        {
144            this.server = new Socket( AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp );
145            this.allDone = new ManualResetEvent( true );
146            this.cmbIP.Items.Clear();
147            foreach( IPAddress ip in Dns.GetHostByName( Dns.GetHostName() ).AddressList )
148            {
149                this.cmbIP.Items.Add( ip.ToString() );
150            }

151            ifthis.cmbIP.Items.Count > 0 )
152                this.cmbIP.SelectedIndex = 0;
153            this.statBar.Text = "初始化完成";
154            this.btnStop.Enabled = false;
155            this.buffer = new byte1024];
156        }

157
158        private void btnStart_Click(object sender, System.EventArgs e)
159        {
160            try
161            {
162                IPEndPoint ipep = new IPEndPoint( IPAddress.Parse( this.cmbIP.Text ),9000 );
163                this.server.Bind( (EndPoint)ipep );
164                this.server.Listen( 10 );
165                this.server.BeginAccept( new AsyncCallback( this.AcceptCallback ),this.server );
166                this.statBar.Text = "服务器" + ipep.ToString() + "正在监听";
167                this.txt.Text = "开始等待客户端连接";
168            }

169            catch( Exception ex )
170            {
171                this.txt.Text += "\r\n" + ex.ToString();
172            }

173        }

174
175        private void AcceptCallback( System.IAsyncResult iar )
176        {
177            if( iar.IsCompleted )
178            {
179                try
180                {
181                    Socket oldServer = (Socket)iar.AsyncState;
182                    Socket client = (Socket)oldServer.EndAccept( iar );                    
183                    this.txt.Text += "\r\n远程客户端:" + client.RemoteEndPoint.ToString() + "连接";
184                    byte[] send = System.Text.Encoding.Default.GetBytes( "服务器端的响应 at " + DateTime.Now.ToString() );    
185                    client.BeginSend( send,0,send.Length,SocketFlags.None,new AsyncCallback(this.SendCallback ),client );
186                }

187                catch( Exception ex )
188                {
189                    this.txt.Text += "\r\n" + ex.ToString();
190                }

191            }

192        }

193
194        private void SendCallback( System.IAsyncResult iar )
195        {
196            try
197            {
198                Socket socket = (Socket)iar.AsyncState;
199                int send = socket.EndSend( iar );
200                this.txt.Text += "\r\n已发送至客户端数据,大小为:" + send.ToString();
201                socket.BeginReceive(this.buffer,0,this.buffer.Length,SocketFlags.None,new AsyncCallback(this.ReceiveCallback),socket );
202            }

203            catch( Exception ex )
204            {
205                this.txt.Text += "\r\n" + ex.ToString();
206            }

207        }

208
209        private void StartReceive()
210        {
211//            this.allDone.Reset();
212//            this.server.BeginReceive( this.buffer,0,this.buffer.Length,SocketFlags.None,new AsyncCallback(this.ReceiveCallback ),this.server );
213//            this.allDone.WaitOne();
214        }

215
216        private void ReceiveCallback( System.IAsyncResult iar )
217        {
218            try
219            {
220                
221                Socket client = (Socket)iar.AsyncState;
222                int recv = client.EndReceive( iar );
223                if( recv == 0 )
224                {
225                    client.Close();
226                    this.txt.Text += "\r\n等待客户端连接..:";
227                    this.server.BeginAccept( new AsyncCallback(this.AcceptCallback),this.server );
228                    return;
229                }

230                string msg = System.Text.Encoding.Default.GetString( this.buffer,0,recv );
231                this.txt.Text += "\r\n从" + client.RemoteEndPoint.ToString() + "接收到的数据是:" + msg;
232                byte[] re = System.Text.Encoding.Default.GetBytes( "服务器端已收到:" + msg );
233                client.BeginSend( re,0,re.Length,SocketFlags.None,new AsyncCallback(this.SendCallback ),client );
234            }

235            catch( Exception ex )
236            {
237                this.txt.Text += "\r\n" + ex.ToString();
238            }

239        }

240    }

241}

242
posted on 2006-08-24 16:35  王员外  阅读(615)  评论(0编辑  收藏  举报