C#异步服务器袜子应用 [英] C# Asynchronous Server Sock Appplication

查看:78
本文介绍了C#异步服务器袜子应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<pre>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.Collections.Generic;
using System.Text;
using System.IO;
		public  void OnDataReceived(IAsyncResult asyn)
		{
			try
			{
				CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
				//end receive...
				int iRx  = 0 ;
				iRx = theSockId.thisSocket.EndReceive (asyn);
				char[] chars = new char[iRx +  1];
				System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
				int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
				System.String szData = new System.String(chars);
                txtDataRx.Text = txtDataRx.Text + szData;
				WaitForData(m_socWorker );
                DateTime currentDate = DateTime.Now;
                long eTicks = currentDate.Ticks;
                System.IO.File.WriteAllText(@"C:\recv\" + eTicks + ".hl7", txtDataRx.Text + szData);
			}
			catch (ObjectDisposedException )
			{
				System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
			}
			catch(SocketException se)
			{
				MessageBox.Show (se.Message );
			}
		}
		private void button1_Click(object sender, System.EventArgs e)
		{
			try
			{
				Object objData = txtDataTx.Text;
				byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
				m_socWorker.Send (byData);
			}
			catch(SocketException se)
			{
				MessageBox.Show (se.Message );
			}
		}

	}
}


我的问题是,只要我写出我从客户端收到的文件,我的程序就会写出700-800次!我验证了这一点,因为我使用CurrentDate刻度作为文件名.我是否可以看到一些消息或事件,所以我知道客户端已完成文件发送,然后只将文件写一次?

谢谢.


Steven Andler


My issue is whenever I write out the file I am receiving from the client side, my program writes it out 700 - 800 times! I verified this because I am and using the CurrentDate ticks as the filename. Is there some message or event I can see so I know the client is done sending the file and then only write the file out once?

Thank you.


Steven Andler

推荐答案

我建​​议:对此问题进行调查,通过消除所有异步调用来简化设计.您可以将它们全部替换为阻塞调用,但可以从单独的线程中调用.这种方法更具逻辑性和直接性,因此将减少很多错误.我真的认为,在大多数情况下,使用异步API的习惯是从线程不像现在这样普遍的时候继承的.

您可以在过去的解决方案中查看我的此类设计草图:众多客户从相同的端口号 [ ^ ].

—SA
I would advise the following: instead investigation on this problem, simplify your design by getting rid of all asynchronous calls. You can replace them all with blocking calls but called from separate threads. This approach is much more logical and straightforward, so it will invite much less bugs. I really think that in most cases the habit of using asynchronous APIs is inherited from the time when threads were not the commonplace as they are now.

You can look at my sketch of such design in my past solution: Multple clients from same port Number[^].

—SA


这篇关于C#异步服务器袜子应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆