Title: Asynchronous communication instance 1 (server)
墨初 知识笔记 86阅读
1 use the system; 2 use the system. Drawing; 3 use the system. Collection; 4 use the system. Component model; 5 use the system. Windows. Forms6 uses this system. Data; 7 use the system. Text; 8 use the system. Net; 9 use the system. Net. Socket s10rgba (0,0,0,1)' uses the system. Threading; Summary of 1112 namespace t server 13 {14/* *//summary15//form1 16///summary17
5, 1)">public class Form1 : System.Windows.Forms.Form18 {
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 if( this.cmbIP.Items.Count > 0 )
152 this.cmbIP.SelectedIndex = 0;
153 this.statBar.Text = "初始化完成";
154 this.btnStop.Enabled = false;
155 this.buffer = new byte[ 1024];
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
标签: