📄 如何写一个稳定,高效的socket服务器程序。 _net技术 - c# - csdn社区 community_csdn_net.htm
字号:
byte[] bCheck; <BR> <BR> protected
AsyncCallback pfnWorkerCallBack ; <BR>
protected AsyncCallback proOnAccept ; <BR>
<BR> /// <summary> <BR> /// 上传文件包
<BR> /// </summary> <BR> public
class TSocketPacket <BR> { <BR> public
System.Net.Sockets.Socket thisSocket; <BR> public
byte[] dataBuffer = new byte[ONCE_COUNT]; <BR>
<BR> public FileStream m_file ; <BR>
public int nTimes ; <BR> public int nCurTime ;
<BR> <BR> public TSocketPacket() <BR> {
<BR> Reset(); <BR> } <BR>
<BR> /// <summary> <BR> /// 清空
<BR> /// </summary> <BR> public void
Reset() <BR> { <BR> <BR> nTimes =
0; <BR> nCurTime = 0; <BR> if(m_file !=
null) <BR> { <BR> try <BR> {
<BR> m_file.Flush(); <BR> m_file.Close(); <BR> }
<BR> catch <BR> { <BR> }
<BR> <BR> finally <BR> { <BR>
m_file = null; <BR> } <BR> } <BR>
<BR> if( thisSocket != null) <BR> { <BR>
try <BR> { <BR> thisSocket.Close(); <BR>
} <BR> catch <BR> { <BR> }
<BR> finally <BR> { <BR> thisSocket = null;
<BR> } <BR> <BR> } <BR>
<BR> } <BR> <BR> // public bool
bCmd = true; <BR> } <BR> <BR> ///
<summary> <BR> /// 应用程序的主入口点。 <BR> ///
</summary> <BR> [STAThread] <BR> static
void Main(string[] args) <BR> {
<BR> // TcpListener myList=new TcpListener(ipAd,PORT);
<BR> // <BR> // myList.Start(); <BR>
<BR> TUploadServer app = new
TUploadServer(); <BR> <BR> if(args.Length
!= 0) <BR> app.CreateWait(Convert.ToInt16(args[0]));
<BR> else <BR> app.CreateWait(); <BR>
<BR> // <BR> // TODO: 在此处添加代码以启动应用程序
<BR> // <BR> } <BR> <BR>
<BR> /// <summary> <BR> /// 构造
<BR> /// </summary> <BR> public
TUploadServer() <BR> { <BR> //Socket Packet
Array <BR> aSock = new TSocketPacket[MAX_CONNECT];
<BR> for(int i = 0; i<
MAX_CONNECT; i++) <BR> aSock[i] = new
TSocketPacket(); <BR> <BR> // byte
process <BR> m_byte = new EIIByte(); <BR>
<BR> nSocketNum = 0; <BR> <BR>
bSend = new byte[ONCE_COUNT]; <BR> <BR>
m_ascn = new ASCIIEncoding(); <BR>
<BR> pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
<BR> <BR> proOnAccept = new
AsyncCallback(OnAccept); <BR> <BR> bCheck = new
Byte[2]; <BR> int pos = 0; <BR>
<BR> m_byte.SetWord(bCheck,CMD_S_CHECK,ref pos); <BR>
// pfnWorkerCallBack = new AsyncCallback(OnReceive);
<BR> <BR> // proOnSend = new
AsyncCallback(OnSend); <BR> <BR> } <BR>
<BR> <BR> /// <summary> <BR>
/// 创建等待连接 <BR> /// </summary>
<BR> public void CreateWait(int port)
<BR> { <BR> int nCount = 0; <BR>
<BR> IPAddress ip =
Dns.GetHostByName(Dns.GetHostName()).AddressList[0]; <BR>
<BR> // IPAddress ipAddress = IPAddress.Parse(IP);
<BR> IPEndPoint ipe = new
IPEndPoint(ip,port); <BR> <BR> sWait = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp); <BR> <BR> sWait.Bind(ipe);
<BR> sWait.Listen(MAX_CONNECT); <BR>
sWait.BeginAccept(proOnAccept,sWait); <BR> <BR>
Console.WriteLine("The server is running at
port {0}...",port); <BR> Console.WriteLine("The local
End point is :" + ip.ToString()
); <BR> Console.WriteLine("Waiting for a
connection....."); <BR> <BR> while(true)
<BR> { <BR> <BR>
System.Threading.Thread.Sleep(50); <BR> nCount ++;
<BR> //每60秒检查一次 <BR> if(nCount >= 1200)
<BR> { <BR> ActiveCheck(); <BR> nCount =
0; <BR> } <BR> } <BR> <BR> }
<BR> <BR> /// <summary> <BR>
/// 创建等待连接 <BR> /// </summary>
<BR> public void CreateWait() <BR> {
<BR> CreateWait(PORT); <BR> <BR> }
<BR> <BR> <BR> /// <summary>
<BR> /// 等待接收数据 <BR> /// </summary>
<BR> /// <param name="nIndex"></param>
<BR> private void WaitForData(int nIndex)
<BR> { <BR> // Console.WriteLine("WaitForData
{0}",soc.RemoteEndPoint.ToString()); <BR> <BR> try
<BR> { <BR> TSocketPacket theSocPkt =
aSock[nIndex]; <BR> <BR> if( theSocPkt
== null) <BR> return ; <BR> //
now start to listen for any data...
<BR> theSocPkt.thisSocket .BeginReceive
(theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length
,SocketFlags.None,pfnWorkerCallBack,nIndex); <BR> }
<BR> <BR> catch(SocketException se) <BR>
{ <BR> ProcessSocketException(se,nIndex); <BR>
<BR> } <BR> <BR> } <BR> <A
href="http://topic.csdn.net/t/20030327/22/1586528.html#">Top</A></P>
<H3><STRONG><A class=anchor name=r_10507990>9 楼</A>gujianxin(木头象)<INPUT class=user5 title="五级用户 该版得分小于等于5000分,大于2000分" type=button></STRONG><SPAN>回复于
2003-03-28 11:35:45 得分 0 </SPAN></H3>
<P>//////////////////////////////// <BR> ////刚用C#时写的,莫笑
<BR> <BR> /// <summary> <BR> ///
接收数据,并处理 <BR> /// </summary> <BR>
/// <param name="asyn"></param> <BR>
public void OnDataReceived(IAsyncResult asyn)
<BR> { <BR> //send : CMD(WORD =
0x0301)+filename's length(WORD)+filename(target)+size(DWORD)+times(WORD),
<BR> //Receive: CMD(WORD = 0x0302)+reday
status(BYTE 1= OK,2 = FAIL) <BR>
<BR> //check <BR> if( !((asyn.AsyncState) is
int)) <BR> return; <BR> <BR>
string sFileName = null; <BR> short nNameLength = 0;
<BR> int nSize = 0; <BR> byte byOper = ALL_RIGHT;
//打开文件操作结果代码 <BR> <BR> int nIndex =
(int)asyn.AsyncState; <BR> <BR> if(nIndex >=
MAX_CONNECT || nIndex <0 )
<BR> return ; <BR> TSocketPacket theSockId
= aSock[nIndex] ; <BR> <BR>
if(theSockId == null) <BR> return ;
<BR> <BR> try <BR> { <BR> //end
receive... <BR> <BR> int iRx =
theSockId.thisSocket.EndReceive (asyn); <BR> //
Console.WriteLine("Received Data From {0},length =
{1}",theSockId.thisSocket.RemoteEndPoint.ToString(),iRx);
<BR> int pos = 0; <BR> <BR> int
nCmd = m_byte.GetWord(theSockId.dataBuffer,ref pos);
<BR> <BR> if(nCmd == CMD_C_REQUERY) //requery
<BR> { <BR> <BR> nNameLength =
m_byte.GetWord(theSockId.dataBuffer,ref pos); <BR>
<BR> sFileName = m_ascn.GetString(theSockId.dataBuffer,pos,nNameLength);
<BR> <BR> pos += nNameLength; <BR>
<BR> nSize = m_byte.GetDword(theSockId.dataBuffer,ref pos);
<BR> <BR> theSockId.nTimes=
m_byte.GetDword(theSockId.dataBuffer,ref pos); <BR>
<BR> Console.WriteLine("Get Requery file =
'{0}',size = {1} ,times=
{2}",sFileName,nSize,theSockId.nTimes); <BR> <BR> //
assert m_file not opened <BR> if
(theSockId.m_file != null) <BR> //return
; <BR> byOper = FILE_ALWAYS_OPENED; <BR>
<BR> try //open the file <BR> {
<BR> <BR> theSockId.m_file =
File.Open(sFileName,FileMode.OpenOrCreate,FileAccess.Write,FileShare.None
); <BR> <BR> Console.WriteLine("Open or
Create file '{0}'",sFileName); <BR> <BR>
byOper = ALL_RIGHT; <BR> <BR> theSockId.nCurTime = 0;
<BR> <BR> } <BR> <BR>
catch(Exception e) <BR> { <BR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -