admin 管理员组文章数量: 887021
2023年12月22日发(作者:grep过滤)
1.简单服务器端/*using ;using s;using ;using ing;private static int port = %%2;private static Thread thThreadRead;private static TcpListener TcpListen;private static bool bListener = true;private static Socket stRead;*/private static void Listen(){ try { TcpListen = new TcpListener(port); (); stRead = Socket(); EndPoint tempRemoteEP = EndPoint; IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP; IPHostEntry host = tByAddress(s); string sHostName = me; while (bListener) { (es(%%1)); string sTime = tTimeString(); Byte[] byRead = new Byte[1024]; int iRead = eFrom(byRead, ref tempRemoteEP); Byte[] byText = new Byte[iRead]; (byRead, 0, byText, 0, iRead); string line = ing(byRead); } } catch (tyException) { //监听失败 }}thThreadRead = new Thread(new ThreadStart(Listen));();2.简单客户端/*using ;using s;using ;private static IPEndPoint dateTimeHost;*/string hostIPString=%%1;string hostPortString=%%2;IPAddress hostIP=(hostIPString);dateTimeHost=new IPEndPoint(hostIP,(hostPortString));Socket conn=new Socket(etwork,,);t(dateTimeHost);int bytes=0;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
Byte[] RecvBytes=new Byte[256];bytes=e(RecvBytes,,0);string RecvString=ing(RecvBytes,0,bytes);ine(RecvString);wn();();3.获得本机IP//using ;IPAddress[] addressList = tByName(tName()).AddressList;string %%1=null;for (int i = 0; i < ; i++){ %%1 += addressList[i].ToString();}4.端对端通信/*using ;using s;*/UdpClient client=new UdpClient(%%2);IPAddress a=("127001");IPEndPoint receivePoint=new IPEndPoint(a,%%2);IPAddress HostIP=null;byte[] sendData=es(%%3);byte[] recData;try{ HostIP=(%%1);}catch { recData=e(ref receivePoint); %%3=ing(recData); (sendData,,%%4,%%2); ();}IPEndPoint host=new IPEndPoint(HostIP,%%2);recData=e(ref receivePoint);%%3=ing(recData);();5.点对点通信/*using ;using s;using ;using ing;*/Thread th;TcpListener tpListen1;bool listenerRun=true;NetworkStream tcpStream;StreamWriter reqStreamW;TcpClient tcpc;Socket skSocket;protected void Listen(){file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
try{ tpListen1=new TcpListener((%%2)); (); skSocket=Socket(); EndPoint tempRemoteEP=EndPoint; IPEndPoint tempRemoteIP=(IPEndPoint)tempRemoteEP; IPHostEntry host=tByAddress(s); string HostName=me; while(listenerRun) { Byte[] stream=new Byte[1024]; string time=ng(); int i=eFrom(stream,ref tempRemoteEP); string %%5=ing(stream); //指定编码,从缓冲区中解析出内容 //time+" "+HostName+":" } } catch(tyException) { //防火墙安全错误! } try{ string sMsg=%%4; string MyName=tName(); reqStreamW=new StreamWriter(tcpStream); (sMsg); (); string time=ng(); //显示传送的数据和时间 //time+" "+MyName+":" //sMsg } catch(Exception)
{ //无法发送信息到目标计算机! } protected override void Dispose(bool disposing) { try{ listenerRun=false; (); th=null; (); (); (); } catch{} if(disposing && component!=null) { e(); } } e(disposing);}file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
对时服务器端/*using ;using ;using s;using ing;using ;*/public void start_server(){ while(true) { byte[] recData=e(ref receivePoint); ASCIIEncoding encode=new ASCIIEncoding(); string Read_str=ing(recData)); string[] tem=Read_('/'); byte[] sendData=es(ng()); (sendData,,temp[0],(temp[1])); }}UdpClient server=new UdpClient(%%1);IPEndPoint receivePoint=new IPEndPoint(new IPAddress("127001",%%1);Thread startServer=new Thread(new ThreadStart(start_server));();protected override void Dispose(bool disposing){ try{ (); (); } catch{} if(disposing && component!=null) { e(); }}e(disposing);}对时客户端/*using ;using ;using s;using pServices;*/[DllImport("")]private static bool SetSystemTime(SystemTime time);public class SystemTime{ public short year; public short Month; public short DayOfWeek; public short Day; public short Hour; public short Minute;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
public short Second; public short Milliseconds;}UdpClient client=new UdpClient(%%2);IPEndPoint receivePoint=new IPEndPoint(a,%%2);IPAddress a=new ("127001");string timeString=ng();DataTime temp;IPAddress HostIP;bool continueLoop=true;while(continueLoop){ string hostName=tName(); ncoding encode=new ncoding(); string sendString=hostName+"/"+%%ng(); byte[] sendData=es(sendString); byte[] recData; try{ HostIP=(%%1); } catch { (sendData,,%%1,%%2); recData=e(ref receivePoint); timeString=ing(recData); (); continueLoop=false; return; } IPEndPoint host=new IPEndPoint(HostIP,%%2); (sendData,,host); recData=e(ref receivePoint); timeString=ing(recData); (); continueLoop=false;}try{ temp=(timeString);}catch { return;}SystemTime st=new SystemTime();=(short);=(short);eek=(short)eek;=(short);=16();if(>=12){ -=(short)8;}else if(>=8){ -=(short)8;}else{file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
+=(short)16;}=16();=16();econds=16(econds);if(SetSystemTime(st)){ //修改成功}else{ //修改不成功}8.点对点传输文件using ;/*命名空间了实现 Berkeley 套接字接口。通过这个类,我们可以实现网络计算机之间的消息传输和发送.而在我下面要讨论的这个议题里,我们将讨论的是用套节子实现文件的传输.这种方法有别于FTP协议实现的的文件传输方法,利用ftp的方法需要一个专门的服务器和客户端,无疑于我们要实现的点对点的文件传输太为复杂了一些。在这里,我们实现一个轻量级的方法来实现点对点的文件传输,这样就达到了intenet上任何两个计算机的文件共享。在两台计算机传输文件之前,必需得先有一台计算机建立套节子连接并绑定一个固定得端口,并在这个端口侦听另外一台计算机的连接请求。*/socket = new Socket(etwork,, );
ng = true ;
IPEndPoint computernode1 = new IPEndPoint(serverIpadress, 8080);(computernode1);(-1);//当有其他的计算机发出连接请求的时候,被请求的计算机将对每一个连接请求分配一个线程,用于处理文件传输和其他服务。while (true){ clientsock = (); if ( ted ) { Thread tc = new Thread(new ThreadStart(listenclient)); (); }}//下面的代码展示了listenclient方法是如何处理另外一台计算机发送过来的请求。首先并对发送过来的请求字符串作出判断,看看是何种请求,然后决定相应的处理方法。void listenclient()
{
Socket sock = clientsock ;
try
{
while ( sock != null )
{
byte[] recs = new byte[32767];
int rcount = e(recs,,0) ;
string message = ing(recs) ;
//对message作出处理,解析处请求字符和参数存储在cmdList 中
execmd=cmdList[0];
file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
sender = null ;
sender = new Byte[32767]; string parm1 = "";
//目录列举
if ( execmd == "LISTING" )
{
ListFiles(message);
continue ;
}
//文件传输
if ( execmd == "GETOK" )
{
cmd = "BEGINSEND " + filepath + " " + filesize ;
sender = new Byte[1024];
sender = es(cmd);
(sender, , 0 );
//转到文件下载处理
DownloadingFile(sock);
continue ;
}
}
}
catch(Exception Se)
{
string s = e;
ine(s);
}
}//至此,基本的工作已经完成了,下面我们看看如何处理文件传输的。
while(rdby < total && te)
{
//从要传输的文件读取指定长度的数据
len =(buffed,0,) ;
//将读取的数据发送到对应的计算机
(buffed, 0,len);
//增加已经发送的长度
rdby=rdby+len ;
}
从上面的代码可以看出是完成文件转换成FileStream 流,然后通过NetworkStream绑定对应的套节子,最后调用他的write方法发送到对应的计算机。
我们再看看接受端是如何接受传输过来的流,并且转换成文件的:
NetworkStream nfs = new NetworkStream(sock) ;
try
{
//一直循环直到指定的文件长度
while(rby < size)
{
byte[] buffer = new byte[1024] ;
//读取发送过来的文件流
int i = (buffer,0,) ;
(buffer,0,(int)i) ;
rby=rby+i ;
}
();}catch(Exception){}file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
/*从上面可以看出接受与发送恰好是互为相反的过程,非常简单。
至此,单方向的文件传输就完成了,只需要在每个对等的节点上同时实现上面的发送和接受的处理代码就可以做到互相传输文件了。*/9.发送邮件//using ;string strSmtpServer=%%1; //"100.100.100.100"string strFrom=%%2; //"someone@"string strFromPass=%%3; //"someone@"string strto=%%4; //"xxxx"string strSubject=%%5;//"webtest"string strBody=%%6; TextBox1SmtpClient client = new SmtpClient(strSmtpServer);aultCredentials = false;tials = new kCredential(strFrom, strFromPass);ryMethod = k;MailMessage message = new MailMessage(strFrom, strto, strSubject, strBody);Attachment attachment = new Attachment("c:");(attachment);coding = 8;Html = true;(message);10.接收邮件/*using s;using ;using graphy;using ;*/// 类名:Pop3
// 功能:接收电子邮件namespace { ///
///
string strToSend = command + "rn"; byte[] arrayToSend = es(Array()); (arrayToSend,0,); } ///
{ strEncode = ing(iStart + 6, - iStart - 6); try { return ormToString(strEncode); } catch(Exception exc) { throw new Pop3Exception(e); } } }#endregion ///
/// Pop3命令行 ///
|| ing(0,4).Equals("UIDL")) //记录STAT后的消息(其中包含邮件数) { strMessage = ReadMultiLine(); if(("LIST")) //记录LIST后的消息(其中包含邮件数) mstrStatMessage = strMessage; } //读取单行 else strMessage = m_ne(); //判断执行结果是否正确 if(CheckCorrect(strMessage,"+OK")) return strMessage; else return "Error"; } catch(IOException exc) { throw new Pop3Exception(ng()); } } ///
return strTemp; } //USER命令 private string USER(string user) { return ExecuteCommand("USER " + user) + "rn"; } //PASS命令 private string PASS(string password) { return ExecuteCommand("PASS " + password) + "rn"; } //LIST命令 private string LIST() { return ExecuteCommand("LIST") + "rn"; } //UIDL命令 private string UIDL() { return ExecuteCommand("UIDL") + "rn"; } //NOOP命令 private string NOOP() { return ExecuteCommand("NOOP") + "rn"; } //STAT命令 private string STAT() { return ExecuteCommand("STAT") + "rn"; } //RETR命令 private string RETR(int number) { return ExecuteCommand("RETR " + ng()) + "rn"; } //DELE命令 private string DELE(int number) { return ExecuteCommand("DELE " + ng()) + "rn"; } //QUIT命令 private void Quit() { WriteToNetStream(ref mnetStream,"QUIT"); }file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
///
/// /// 用户名 /// 口令file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
///
12.多线程非阻塞通信13.多线程文件断点续传////Thead.h// 线程对象封装//#ifndef _THREAD_INCLUDE_#define _THREAD_INCLUDE_class CThread{private: static DWORD WINAPI ThreadProc(LPVOID pVoid);protected: BOOL m_bTerminated; // 线程是否终止的标志 virtual void Execute(void) = 0;public: HANDLE m_hThread; // 线程句柄 CThread(void); ~CThread(void); void Resume(void); void Terminate(void); HANDLE GetThreadHandle(void);};#endif // #ifndef _THREAD_INCLUDE_//// 线程对象封装//#include "stdafx.h"#include "Thread.h"CThread::CThread(void){ m_bTerminated = FALSE; DWORD dwThreadID; m_hThread = CreateThread(NULL, 0, ThreadProc, this, CREATE_SUSPENDED, &dwThreadID);}CThread::~CThread(void){ CloseHandle(m_hThread); m_hThread = NULL;}DWORD CThread::ThreadProc(LPVOID pVoid){ ((CThread *)(pVoid))->Execute(); return 0;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
}void CThread::Resume(void){ ResumeThread(m_hThread);}void CThread::Terminate(void){ m_bTerminated = TRUE;}HANDLE CThread::GetThreadHandle(void){ return m_hThread;}m_pTcpClient = new CTcpClient(this);m_strServerIp = "127.0.0.1";m_nPort = 8000;m_dwPackageSize = 1024;m_strFileName = "d:";UpdateData(FALSE);m_pTcpClient->SetOnSocketSendErr(OnSocketSendErr);m_pTcpClient->SetOnSocketRecvErr(OnSocketRecvErr);m_pTcpClient->SetOnSocketClose(OnSocketClose);m_pTcpClient->SetOnOneNetMsg(OnOneNetMsg);m_pTcpClient->SetOnSendFileSucc(OnSendFileSucc);m_pTcpClient->SetOnSendFileFail(OnSendFileFail);m_pTcpClient->SetOnSendFileRefuseRecv(OnSendFileRefuseRecv);m_pTcpClient->SetOnSendFileCancelRecv(OnSendFileCancelRecv);m_pTcpClient->SetOnSendFileRecvFail(OnSendFileRecvFail);m_pTcpClient->SetOnSendFileProgress(OnSendFileProgress);CStatic m_ctlCnnStatus;CStatic m_ctlInfo;DWORD m_dwPackageSize;CString m_strServerIp;int m_nPort;CString m_strFileName;CString m_strMsg;void CSendDlg::OnConnect()
{ if(!UpdateData()) return; m_pTcpClient->SetAddr((char *)(LPCTSTR)m_strServerIp); m_pTcpClient->SetPort(m_nPort); m_pTcpClient->SetPackageSize(m_dwPackageSize); m_dowText("请等待..."); if(!m_pTcpClient->Connect()) m_dowText("连接失败!"); else m_dowText("已连接");file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
}void CSendDlg::OnDisconnect()
{ m_pTcpClient->Disconnect(); m_dowText("断开连接");}void CSendDlg::OnSendFile()
{ if(!UpdateData()) return; m_pTcpClient->SetPackageSize(m_dwPackageSize); if(!m_pTcpClient->SendFile((char *)(LPCTSTR)m_strFileName)) AfxMessageBox("发生文件失败");}void CSendDlg::OnSendMsg(void){ char s[99999]; if(!UpdateData()) return; sprintf(s, "@00000001%s", m_strMsg); m_pTcpClient->SendNetMsg(s, strlen(s) - 6);}void CSendDlg::OnSocketSendErr(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->m_dowText("发送数据出错");}void CSendDlg::OnSocketRecvErr(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->m_dowText("接收数据出错");}void CSendDlg::OnSocketClose(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->m_dowText("断开连接");}void CSendDlg::OnOneNetMsg(void *pNotifyObj, char *Msg, int nMsgLen){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; char s[9999]; CString strInfo; strncpy(s, Msg, nMsgLen); s[nMsgLen] = 0;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
strInfo = s; pSendDlg->DispInfo(strInfo);}void CSendDlg::OnSendFileSucc(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileSucc");}void CSendDlg::OnSendFileFail(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileFail");}// 接收方拒绝接收文件void CSendDlg::OnSendFileRefuseRecv(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileRefuseRecv");}// 接收方拒绝文件void CSendDlg::OnSendFileCancelRecv(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileCancelRecv");}// 接收方取消接收void CSendDlg::OnSendFileRecvFail(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileRecvFail");}void CSendDlg::OnSendFileProgress(void *pNotifyObj, int nSentBytes, int nTotalBytes){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; CString strInfo; ("%d / %d", nSentBytes, nTotalBytes); pSendDlg->DispInfo(strInfo);}void CSendDlg::DispInfo(CString strInfo){ m_dowText(strInfo);}file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
void CSendDlg::OnCancelSend()
{ m_pTcpClient->CancelSendFile();
}void CSendDlg::OnDestroy()
{ CDialog::OnDestroy(); m_pTcpClient->Disconnect();}delete m_pTcpClient;//#include "Shlwapi.h"// 判断文件是否存在BOOL IsFileExists(char *pszPathName);// 创建多层目录,成功返回TRUE,识别返回FALSEBOOL ForceDirectories(char *pszDir);// 扩展文件操作BOOL DeleteFileEx(char *szPathName, BOOL bAllowUndo = FALSE);BOOL RenameFileEx(char *szOldPathName, char *szNewPathName);BOOL MoveFileEx(char *szSrcPathName, char *szDstPathName);BOOL CopyFileEx(char *szSrcPathName, char *szDstPathName);// 重新启动操作系统BOOL RebootWindows();// 设置程序是否在操作系统启动后自动运行void SetAutoRun(BOOL bEnable);BOOL ShutDownWin98();BOOL ShutDownWinNT();BOOL IsLegalFileName(char *szFileName);m_pTcpServer1 = new CTcpServer(this);m_pTcpServer1->SetBindAddr("");m_pTcpServer1->SetPort(8000);m_pTcpServer1->SetOnAccept(OnAccept);m_pTcpServer1->SetOnAcceptErr(OnAcceptErr);m_pTcpServer1->SetOnSocketConnect(OnSocketConnect);m_pTcpServer1->SetOnSocketDisconnect(OnSocketDisconnect);m_pTcpServer1->SetOnSocketSendErr(OnSocketSendErr);m_pTcpServer1->SetOnSocketRecvErr(OnSocketRecvErr);m_pTcpServer1->SetOnOneNetMsg(OnOneNetMsg);m_pTcpServer1->SetOnRecvFileStart(OnRecvFileStart);m_pTcpServer1->SetOnRecvFileProgress(OnRecvFileProgress);m_pTcpServer1->SetOnRecvFileFail(OnRecvFileFail);m_pTcpServer1->SetOnRecvFileSucc(OnRecvFileSucc);m_pTcpServer1->SetOnRecvFileCancel(OnRecvFileCancel);if(!m_pTcpServer1->StartAccept()){ AfxMessageBox("开始服务失败"); return FALSE;}void CRecvDlg::OnAccept(void *pNotifyObj, SOCKET hSocket, BOOL &bAccept){file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnAccept-%d", hSocket); pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnAcceptErr(void *pNotifyObj, SOCKET hAccept){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnAcceptErr-%d", hAccept); pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnOneNetMsg(void *pNotifyObj, char *Msg, int nMsgLen){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; char s[10240]; memcpy(s, Msg, nMsgLen); s[nMsgLen] = 0; strInfo = (LPCTSTR)s; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileStart(void *pNotifyObj, char *szPathName, BOOL &bRecv){}void CRecvDlg::OnRecvFileProgress(void *pNotifyObj, DWORD dwRecvedBytes, DWORD dwFileSize){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("%d / %d", dwRecvedBytes, dwFileSize); pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileSucc(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileSucc"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileFail(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileFail"; pRecvDlg->DispInfo(strInfo);}file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
void CRecvDlg::OnRecvFileCancel(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileCancel"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::DispInfo(CString &strInfo){ m_dowText(strInfo);}void CRecvDlg::DispCnnCount(void){ CString strCnnCount; ("%d", m_pTcpServer1->GetClientCount()); m_dowText(strCnnCount);}void CRecvDlg::OnCancelRecv()
{ m_pTcpServer1->CancelAllRecvFile();}void CRecvDlg::OnSocketConnect(void *pNotifyObj, SOCKET hSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnSocketConnect-%d", hSocket); pRecvDlg->DispInfo(strInfo); pRecvDlg->DispCnnCount();}void CRecvDlg::OnSocketDisconnect(void *pNotifyObj, SOCKET hSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnSocketDisconnect-%d", hSocket); pRecvDlg->DispInfo(strInfo); pRecvDlg->DispCnnCount();}void CRecvDlg::OnSocketSendErr(void *pNotifyObj, CServerClientSocket *pServerClientSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnSocketSendErr"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnSocketRecvErr(void *pNotifyObj, CServerClientSocket *pServerClientSocket){file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnSocketRecvErr"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnCloseCnn()
{}void CRecvDlg::OnDestroy()
{ CDialog::OnDestroy(); m_pTcpServer1->CloseAllServerClientSocket();
}delete m_pTcpServer1;m_pTcpServer1 = NULL;14.多线程多文件断点续传////Thead.h// 线程对象封装//#ifndef _THREAD_INCLUDE_#define _THREAD_INCLUDE_class CThread{private: static DWORD WINAPI ThreadProc(LPVOID pVoid);protected: BOOL m_bTerminated; // 线程是否终止的标志 virtual void Execute(void) = 0;public: HANDLE m_hThread; // 线程句柄 CThread(void); ~CThread(void); void Resume(void); void Terminate(void); HANDLE GetThreadHandle(void);};#endif // #ifndef _THREAD_INCLUDE_//// 线程对象封装//#include "stdafx.h"#include "Thread.h"CThread::CThread(void){file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
m_bTerminated = FALSE; DWORD dwThreadID; m_hThread = CreateThread(NULL, 0, ThreadProc, this, CREATE_SUSPENDED, &dwThreadID);}CThread::~CThread(void){ CloseHandle(m_hThread); m_hThread = NULL;}DWORD CThread::ThreadProc(LPVOID pVoid){ ((CThread *)(pVoid))->Execute(); return 0;}void CThread::Resume(void){ ResumeThread(m_hThread);}void CThread::Terminate(void){ m_bTerminated = TRUE;}HANDLE CThread::GetThreadHandle(void){ return m_hThread;}m_pTcpClient = new CTcpClient(this);m_strServerIp = "127.0.0.1";m_nPort = 8000;m_dwPackageSize = 1024;m_strFileName = "d:";UpdateData(FALSE);m_pTcpClient->SetOnSocketSendErr(OnSocketSendErr);m_pTcpClient->SetOnSocketRecvErr(OnSocketRecvErr);m_pTcpClient->SetOnSocketClose(OnSocketClose);m_pTcpClient->SetOnOneNetMsg(OnOneNetMsg);m_pTcpClient->SetOnSendFileSucc(OnSendFileSucc);m_pTcpClient->SetOnSendFileFail(OnSendFileFail);m_pTcpClient->SetOnSendFileRefuseRecv(OnSendFileRefuseRecv);m_pTcpClient->SetOnSendFileCancelRecv(OnSendFileCancelRecv);m_pTcpClient->SetOnSendFileRecvFail(OnSendFileRecvFail);m_pTcpClient->SetOnSendFileProgress(OnSendFileProgress);CStatic m_ctlCnnStatus;CStatic m_ctlInfo;DWORD m_dwPackageSize;CString m_strServerIp;int m_nPort;CString m_strFileName;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
CString m_strMsg;void CSendDlg::OnConnect()
{ if(!UpdateData()) return; m_pTcpClient->SetAddr((char *)(LPCTSTR)m_strServerIp); m_pTcpClient->SetPort(m_nPort); m_pTcpClient->SetPackageSize(m_dwPackageSize); m_dowText("请等待..."); if(!m_pTcpClient->Connect()) m_dowText("连接失败!"); else m_dowText("已连接");}void CSendDlg::OnDisconnect()
{ m_pTcpClient->Disconnect(); m_dowText("断开连接");}void CSendDlg::OnSendFile()
{ if(!UpdateData()) return; m_pTcpClient->SetPackageSize(m_dwPackageSize); if(!m_pTcpClient->SendFile((char *)(LPCTSTR)m_strFileName)) AfxMessageBox("发生文件失败");}void CSendDlg::OnSendMsg(void){ char s[99999]; if(!UpdateData()) return; sprintf(s, "@00000001%s", m_strMsg); m_pTcpClient->SendNetMsg(s, strlen(s) - 6);}void CSendDlg::OnSocketSendErr(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->m_dowText("发送数据出错");}void CSendDlg::OnSocketRecvErr(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
pSendDlg->m_dowText("接收数据出错");}void CSendDlg::OnSocketClose(void *pNotifyObj, SOCKET hSocket){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->m_dowText("断开连接");}void CSendDlg::OnOneNetMsg(void *pNotifyObj, char *Msg, int nMsgLen){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; char s[9999]; CString strInfo; strncpy(s, Msg, nMsgLen); s[nMsgLen] = 0; strInfo = s; pSendDlg->DispInfo(strInfo);}void CSendDlg::OnSendFileSucc(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileSucc");}void CSendDlg::OnSendFileFail(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileFail");}// 接收方拒绝接收文件void CSendDlg::OnSendFileRefuseRecv(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileRefuseRecv");}// 接收方拒绝文件void CSendDlg::OnSendFileCancelRecv(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; pSendDlg->DispInfo("OnSendFileCancelRecv");}// 接收方取消接收void CSendDlg::OnSendFileRecvFail(void *pNotifyObj, char *szPathName){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj;file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
pSendDlg->DispInfo("OnSendFileRecvFail");}void CSendDlg::OnSendFileProgress(void *pNotifyObj, int nSentBytes, int nTotalBytes){ CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; CString strInfo; ("%d / %d", nSentBytes, nTotalBytes); pSendDlg->DispInfo(strInfo);}void CSendDlg::DispInfo(CString strInfo){ m_dowText(strInfo);}void CSendDlg::OnCancelSend()
{ m_pTcpClient->CancelSendFile();
}void CSendDlg::OnDestroy()
{ CDialog::OnDestroy(); m_pTcpClient->Disconnect();}delete m_pTcpClient;//#include "Shlwapi.h"// 判断文件是否存在BOOL IsFileExists(char *pszPathName);// 创建多层目录,成功返回TRUE,识别返回FALSEBOOL ForceDirectories(char *pszDir);// 扩展文件操作BOOL DeleteFileEx(char *szPathName, BOOL bAllowUndo = FALSE);BOOL RenameFileEx(char *szOldPathName, char *szNewPathName);BOOL MoveFileEx(char *szSrcPathName, char *szDstPathName);BOOL CopyFileEx(char *szSrcPathName, char *szDstPathName);// 重新启动操作系统BOOL RebootWindows();// 设置程序是否在操作系统启动后自动运行void SetAutoRun(BOOL bEnable);BOOL ShutDownWin98();BOOL ShutDownWinNT();BOOL IsLegalFileName(char *szFileName);m_pTcpServer1 = new CTcpServer(this);m_pTcpServer1->SetBindAddr("");m_pTcpServer1->SetPort(8000);m_pTcpServer1->SetOnAccept(OnAccept);m_pTcpServer1->SetOnAcceptErr(OnAcceptErr);file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
m_pTcpServer1->SetOnSocketConnect(OnSocketConnect);m_pTcpServer1->SetOnSocketDisconnect(OnSocketDisconnect);m_pTcpServer1->SetOnSocketSendErr(OnSocketSendErr);m_pTcpServer1->SetOnSocketRecvErr(OnSocketRecvErr);m_pTcpServer1->SetOnOneNetMsg(OnOneNetMsg);m_pTcpServer1->SetOnRecvFileStart(OnRecvFileStart);m_pTcpServer1->SetOnRecvFileProgress(OnRecvFileProgress);m_pTcpServer1->SetOnRecvFileFail(OnRecvFileFail);m_pTcpServer1->SetOnRecvFileSucc(OnRecvFileSucc);m_pTcpServer1->SetOnRecvFileCancel(OnRecvFileCancel);if(!m_pTcpServer1->StartAccept()){ AfxMessageBox("开始服务失败"); return FALSE;}void CRecvDlg::OnAccept(void *pNotifyObj, SOCKET hSocket, BOOL &bAccept){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnAccept-%d", hSocket); pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnAcceptErr(void *pNotifyObj, SOCKET hAccept){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnAcceptErr-%d", hAccept); pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnOneNetMsg(void *pNotifyObj, char *Msg, int nMsgLen){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; char s[10240]; memcpy(s, Msg, nMsgLen); s[nMsgLen] = 0; strInfo = (LPCTSTR)s; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileStart(void *pNotifyObj, char *szPathName, BOOL &bRecv){}void CRecvDlg::OnRecvFileProgress(void *pNotifyObj, DWORD dwRecvedBytes, DWORD dwFileSize){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("%d / %d", dwRecvedBytes, dwFileSize);file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileSucc(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileSucc"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileFail(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileFail"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnRecvFileCancel(void *pNotifyObj, char *szPathName){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnRecvFileCancel"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::DispInfo(CString &strInfo){ m_dowText(strInfo);}void CRecvDlg::DispCnnCount(void){ CString strCnnCount; ("%d", m_pTcpServer1->GetClientCount()); m_dowText(strCnnCount);}void CRecvDlg::OnCancelRecv()
{ m_pTcpServer1->CancelAllRecvFile();}void CRecvDlg::OnSocketConnect(void *pNotifyObj, SOCKET hSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnSocketConnect-%d", hSocket); pRecvDlg->DispInfo(strInfo); pRecvDlg->DispCnnCount();}void CRecvDlg::OnSocketDisconnect(void *pNotifyObj, SOCKET hSocket){file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; ("OnSocketDisconnect-%d", hSocket); pRecvDlg->DispInfo(strInfo); pRecvDlg->DispCnnCount();}void CRecvDlg::OnSocketSendErr(void *pNotifyObj, CServerClientSocket *pServerClientSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnSocketSendErr"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnSocketRecvErr(void *pNotifyObj, CServerClientSocket *pServerClientSocket){ CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo = "OnSocketRecvErr"; pRecvDlg->DispInfo(strInfo);}void CRecvDlg::OnCloseCnn()
{}void CRecvDlg::OnDestroy()
{ CDialog::OnDestroy(); m_pTcpServer1->CloseAllServerClientSocket();
}delete m_pTcpServer1;m_pTcpServer1 = NULL;15.截取屏幕/*using pServices;[DllImport("")]public static extern bool BitBlt(int hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,int hdcSrc,int
nXSrc,int nYSrc,int dwRop);[DllImport("")]public static extern int CreateCompatibleBitmap(int hdc,int nWidth,int nHeight);[DllImport("")]public static extern int CreateCompatibleDC(int hdc);[DllImport("")]public static extern bool DeleteDC(int hdc);[DllImport("")]public static extern bool DeleteObject(int hObject);[DllImport("")]public static extern int GetDeviceCaps(int hdc,int nIndex);[DllImport("")]public static extern int SelectObject(int hdc,int hgdiobj);[DllImport("")]public static extern int GetDesktopWindow();file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
[DllImport("")]public static extern int GetWindowDC(int hWnd);[DllImport("")]public static extern int ReleaseDC(int hWnd,int hDC);*/// Captures the current on-screen representation using Windows API callspublic Bitmap CaptureScreen(){ // Provides a pointer to the visual representation of the desktop window int source= GetWindowDC(GetDesktopWindow()); // Secures the image using CreateCompatibleBitmap int bitmap= CreateCompatibleBitmap(source, GetDeviceCaps(source,8), GetDeviceCaps(source,10)); int destination= CreateCompatibleDC(source); SelectObject(destination, bitmap); BitBlt(destination,0,0, GetDeviceCaps(source,8), GetDeviceCaps(source,10), source,0,0,0x00CC0020); Bitmap image= GetImage(bitmap); Cleanup(bitmap, source, destination); return image;}private void Cleanup(int bitmap,int source,int destination){ ReleaseDC(GetDesktopWindow(), source); DeleteDC(destination); DeleteObject(bitmap);}private Bitmap GetImage(int hBitmap){ Bitmap image= new Bitmap(itmap(new IntPtr(hBitmap)), itmap(new
IntPtr(hBitmap)).Width, itmap(new IntPtr(hBitmap)).Height); return image;}16.聊天室服务器端逻辑using ;using s;using ;using ing;using tions;class Server{ private static List
} public List
private static bool bListener = true; private static TcpListener TcpListen; public Service(Server server, Socket client) { TcpClient tcpc; Socket stSend = null; bool tcpConnect = false; try { stSend = new Socket(etwork, , ); EndPoint tempRemoteEP = EndPoint; IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP; EndPoint epTemp = (EndPoint)tempRemoteIP; t(epTemp); tcpConnect = true; } catch (Exception) { //("目标计算机拒绝了连接请求!"); } finally { if (tcpConnect)file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
{ (); } } } public static void run() { while (true) { stRead = Socket(); EndPoint tempRemoteEP = EndPoint; IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP; IPHostEntry host = tByAddress(s); string sHostName = me; while (bListener) { string sTime = tTimeString(); Byte[] byRead = new Byte[1024]; int iRead = eFrom(byRead, ref tempRemoteEP); Byte[] byText = new Byte[iRead]; (byRead, 0, byText, 0, iRead); string line = ing(byRead); } } } static void Main(string[] args) { }}17.聊天室客户端逻辑/*类似qq聊天工具你看看。。这是客服端的代码:using System;using c;using entModel;using ;using g;using ;using ;using ;using ing;using ;using s;namespace demo2{public partial class frmTouchWe : Form{Thread a;//发送IP跟端口private UdpClient udp = new UdpClient("127.0.0.1",9000);//接收端口private UdpClient udpSend = new UdpClient(8000);file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
private IPEndPoint ip = new IPEndPoint(,0);public frmTouchWe(){InitializeComponent();orIllegalCrossThreadCalls = false;}private void frmTouchWe_Load(object sender, EventArgs e){ //定义线程开始a = new Thread(new ThreadStart(Run));(); }private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){//客服接收信息。弹出窗体frmAnswerInfo answerInfo = new frmAnswerInfo();(); }private void button1_Click(object sender, EventArgs e){//在自己的信息栏中显示自己的信息();//用户信息内容string Mes = ;//用户信息string mes = "用户:"++"("++")"+" " + time;//转换成字节byte[] b = es(Mes);byte[] bb = es(mes);//发送信息(bb, );(b, ); = "";}//循环接受客服发来的信息private void Run(){while (true){byte[] b = e(ref ip);string mes = ing(b);(mes);}}private void button2_Click(object sender, EventArgs e){();}private void button3_Click_1(object sender, EventArgs e){//清空所有项();}file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
}}下面是服务器端的代码using System;using c;using entModel;using ;using g;using ;using ;using ;using ing;using ;using s;namespace demo2{public partial class frmAnswerInfo : Form{//定义一条线程,用来循环接收客户发来的信息Thread a;//定义另一条线程,用来升起窗体Thread b;//发送到信息的地址private UdpClient udpSend = new UdpClient("127.0.0.1",8000);//接收端口private UdpClient udp = new UdpClient(9000);private IPEndPoint ip = new IPEndPoint(,0);public frmAnswerInfo(){InitializeComponent();orIllegalCrossThreadCalls = false;}//循环接收信息private void Run(){while (true){byte[] b = e(ref ip);string mes = ing(b);(mes);}}private void frmAnswerInfo_Load(object sender, EventArgs e){//设置窗体的位置属性(窗体加载时候慢慢从右下角升上来~类似qq广告~~) = ; = - ;//设置窗体的名字
a = new Thread(new ThreadStart(Run));b = new Thread(new ThreadStart(run));//开始线程file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
();();}//用户点击谈话时显示该窗体private void run(){while (true){ = - 10;(100);if ( - >= ){break;}}}//发送按钮编码private void button1_Click(object sender, EventArgs e){
//获取当前时间DateTime time = ;//在自己的信息栏中显示自己发出去的信息("在线客服:"+time);();//在客户端显示自己的信息标题string mes = "在线客服:"+time;//信息内容string Mes = ;//发送信息标题byte[] b = es(mes);//发送信息内容byte[] bb = es(Mes);(b, );(bb,); = "";}private void button2_Click(object sender, EventArgs e){();}private void button3_Click(object sender, EventArgs e){//清除所有项();}}}*/18.克隆对象/docs/docs/16////
/// BaseObject类是一个用来继承的抽象类。
file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
/// 每一个由此类继承而来的类将自动支持克隆方法。
/// 该类实现了Icloneable接口,并且每个从该对象继承而来的对象都将同样地
/// 支持Icloneable接口。
///
public abstract class BaseObject : ICloneable
{
///
/// 克隆对象,并返回一个已克隆对象的引用
///
///
public object Clone()
{
//首先我们建立指定类型的一个实例
object newObject = Instance(e());
//我们取得新的类型实例的字段数组。
FieldInfo[] fields = e().GetFields();
int i = 0;
foreach (FieldInfo fi in e().GetFields())
{
//我们判断字段是否支持ICloneable接口。
Type ICloneType = erface("ICloneable", true);
if (ICloneType != null)
{
//取得对象的Icloneable接口。
ICloneable IClone = (ICloneable)ue(this);
//我们使用克隆方法给字段设定新值。
fields[i].SetValue(newObject, ());
}
else
{
// 如果该字段部支持Icloneable接口,直接设置即可。
fields[i].SetValue(newObject, ue(this));
}
//现在我们检查该对象是否支持IEnumerable接口,如果支持,
//我们还需要枚举其所有项并检查他们是否支持IList 或 IDictionary 接口。
Type IEnumerableType = erface("IEnumerable", true);
if (IEnumerableType != null)
{
//取得该字段的IEnumerable接口
IEnumerable IEnum = (IEnumerable)ue(this);
Type IListType = fields[i].erface("IList", true);
Type IDicType = fields[i].erface("IDictionary", true);
int j = 0;
if (IListType != null)
{
//取得IList接口。
IList list = (IList)fields[i].GetValue(newObject);
foreach (object obj in IEnum)
{
//查看当前项是否支持支持ICloneable 接口。
ICloneType = e().GetInterface("ICloneable", true);
if (ICloneType != null)
{
//如果支持ICloneable 接口,
//我们用它李设置列表中的对象的克隆
ICloneable clone = (ICloneable)obj;
file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
list[j] = ();
}
//注意:如果列表中的项不支持ICloneable接口,那么
//在克隆列表的项将与原列表对应项相同
//(只要该类型是引用类型)
j++;
}
}
else if (IDicType != null)
{
//取得IDictionary 接口
IDictionary dic = (IDictionary)fields[i].GetValue(newObject);
j = 0;
foreach (DictionaryEntry de in IEnum)
{
//查看当前项是否支持支持ICloneable 接口。
ICloneType = e().
GetInterface("ICloneable", true);
if (ICloneType != null)
{
ICloneable clone = (ICloneable);
dic[] = ();
}
j++;
}
}
}
i++;
}
return newObject;
}
}
如何使用
让你的类支持Icloneable接口所要做的就是,将你的类继承自如下所述的BaseObject类:
public class MyClass : BaseObject
{
public string myStr ="test";
public int id;
}
public class MyContainer : BaseObject
{
public string name = "test2";
public MyClass[] myArray= new MyClass[5];
public class MyContainer()
{
for(int i=0 ; i<5 ; i++)
{
y[I] = new MyClass();
}
}
}
现在在Main方法中加入如下代码:
static void Main(string[] args)
file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
{
MyContainer con1 = new MyContainer();
MyContainer con2 = (MyContainer)();
y[0].id = 5;
}
属性文件解析/*using ;using ;import .*;import s.*;import .*;import .*;throws ParserConfigurationException, SAXException, IOException {*/DocumentBuilderFactory dbf=tance();DocumentBuilder db=umentBuilder();Document doc=(%%1); //""ize();NodeList nl=mentsByTagName("book");for(int i=0;i 读取XML配置文件/*using ;using ;import .*;import s.*;import .*;import .*;*/try { DocumentBuilderFactory dbf = tance(); DocumentBuilder db; db = umentBuilder(); Document doc; doc = (""); ize(); NodeList nl = mentsByTagName("book"); for (int i = 0; i < gth(); i++) { Element e = (Element) (i); String strurl = mentsByTagName("dbsource").item(0) .getFirstChild().getNodeValue(); String username; if (mentsByTagName("username").item(0).getFirstChild() == null) { username = ""; } else { username = mentsByTagName("username").item(0)file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] .getFirstChild().getNodeValue(); } String password; if (mentsByTagName("username").item(0).getFirstChild() == null) { password = ""; } else { password = mentsByTagName("password").item(0) .getFirstChild().getNodeValue(); } // strurl // username // password }} catch (ParserConfigurationException e1) { // TODO Auto-generated catch block tackTrace();} catch (SAXException e2) { // TODO Auto-generated catch block tackTrace();} catch (IOException e3) { // TODO Auto-generated catch block tackTrace();}-->属性文件构造/*using ;using ;import .*;import s.*;import .*;import .*;throws ParserConfigurationException, SAXException, IOException {*/DocumentBuilderFactory dbf=tance();DocumentBuilder db=umentBuilder();Document doc=(%%1); //""ize();NodeList nl=mentsByTagName("book");for(int i=0;i { XmlNode childNode; XmlNode brotherNode; bool pd; try { if( ldNodes ==true) { childNode = SelectedNodes(hild); return (childNode); } else { (); if( bling != null) { attrColl = bling; } else { while(bling == null) { (ng()); attrColl = Node; } attrColl = bling; // ("PPP"); } return ( SelectedNodes( attrColl)); } } catch { } return attrColl;}// XmlDocument doc = new XmlDocument();("localhost/"); //Create an attribute collection. // XmlNode attrColl = SingleNode("//book");attrColl = SingleNode("//book/*");edNodes(attrColl);文件节点遍历查找file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] /*using ;private XmlDocument doc = new XmlDocument();private XmlNode attrColl;*/private XmlNode SelectedNodes( XmlNode attrColl){ XmlNode childNode; XmlNode brotherNode; bool pd; try { if( ldNodes ==true) { childNode = SelectedNodes(hild); return (childNode); } else { (); if( bling != null) { attrColl = bling; } else { while(bling == null) { (ng()); attrColl = Node; } attrColl = bling; // ("PPP"); } return ( SelectedNodes( attrColl)); } } catch { } return attrColl;}// XmlDocument doc = new XmlDocument();("localhost/"); //Create an attribute collection. file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] // XmlNode attrColl = SingleNode("//book");attrColl = SingleNode("//book/*");edNodes(attrColl);ngusing System; namespace Remotable { public class RemotableType : MarshalByRefObject { private string _internalString = "This is the RemotableType."; public string StringMethod() { return _internalString; } } } using System; using ng; namespace RemotingFirst { public class Listener { public static void Main() { ure(""); ine("Listening for requests. Press Enter to exit"); ne(); } } } using System; using ng; namespace Client { public class Client { public static void Main() { ure(""); file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] bleType remoteObject = new bleType(); ine(Method()); } } } mode="Singleton" type="bleType, RemotableType" objectUri="" /> 25.实只要用到Socket联接,基本上就得使用Thread,是交叉使用的。 C#封装的Socket用法基本上不算很复杂,只是不知道托管之后的Socket有没有其他性能或者安全上的问题。 在C#里面能找到的最底层的操作也就是socket了,概念不做解释。 程序模型如下: WinForm程序 : 启动端口侦听;监视Socket联接情况;定期关闭不活动的联接; Listener:处理Socket的Accept函数,侦听新链接,建立新Thread来处理这些联接(Connection)。 Connection:处理具体的每一个联接的会话。 1:WinForm如何启动一个新的线程来启动Listener: //start the server private void btn_startServer_Click(object sender, EventArgs e) { //_d = false; Thread _createServer = new Thread(new ThreadStart(WaitForConnect)); _(); } //wait all connections private void WaitForConnect() { SocketListener listener = new SocketListener(32(_)); istening(); } 因为侦听联接是一个循环等待的函数,所以不可能在WinForm的线程里面直接执行,不然Winform也就是无法继续任何操作了,所以才指定一个新的线程来执行这个函数,启动侦听循环。 这一个新的线程是比较简单的,基本上没有启动的参数,直接指定处理函数就可以了。 2:Listener如何启动循环侦听,并且启动新的带有参数的线程来处理Socket联接会话。 先看如何建立侦听:(StartListening函数) file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] IPEndPoint localEndPoint = new IPEndPoint(_ipAddress, _port); // Create a TCP/IP socket. Socket listener = new Socket(etwork, , ); // Bind the socket to the local endpoint and listen for incoming connections. try { (localEndPoint); (20);//20 trucks // Start listening for connections. while (true) { // here will be suspended while waiting for a new connection. Socket connection = (); ("Connect", ng());//log it, new connection …… } }/*基本步骤比较简单: 建立本机的IPEndPoint对象,表示以本机为服务器,在指定端口侦听; 然后绑定到一个侦听Socket上; 进入while循环,等待新的联接; 如果有新的联接,那么建立新的socket来对应这个联接的会话。 值得注意的就是这一句联接代码:()。执行这一句的时候,程序就在这个地方等待,直到有新的联检请求的时候程序才会执行下一句。这是同步执行,当然也可以异步执行。 新的联接Socket建立了(Accept之后),对于这些新的socket该怎么办呢?他们依然是一个循环等待,所以依然需要建立新的Thread给这些Socket去处理会话(接收/发送消息),而这个Thread就要接收参数了。 Thread本身是不能接收参数的,为了让它可以接收参数,可以采用定义新类,添加参数作为属性的方法来解决。 因为每一个Socket是一个Connection周期,所以我定义了这么一个类public class Connection。这个类至少有这样一个构造函数public Connection(Socket socket); 之所以这么做,就是为了把Socket参数传给这个Connection对象,然后好让Listener启动这个Thread的时候,Thread可以知道他正在处理哪一个Socket。 具体处理的方法:(在Listener的StartListening函数,ocket connection = ();之后) Connection gpsCn = new Connection(connection); //each socket will be wait for data. keep the connection. Thread thread = new Thread(new ThreadStart(rSendData)); = ng(); (); 如此一来,这个新的socket在Accept之后就在新的Thread中运行了。 3:Connection的会话处理 建立了新的Connection(也就是socket),远程就可以和这个socket进行会话了,无非就是send和receive。 现在先看看怎么写的这个线程运行的Connection. WaitForSendData函数 */while (true) { bytes = new byte[1024]; string data = ""; //systm will be waiting the msg of receive envet. like Accept(); //here will be suspended while waiting for socket income msg. int bytesRec = this._e(bytes); _lastConnectTime = ; if (bytesRec == 0)//close envent { ("Close Connection", _ng()); break; file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] } data += ing(bytes, 0, bytesRec); //…….handle your data. }/*可以看到这个处理的基本步骤如下: 执行Receive函数,接收远程socket发送的信息; 把信息从字节转换到string; 处理该信息,然后进入下一个循环,继续等待socket发送新的信息。 值得注意的有几个: 1:Receive函数。这个函数和Listener的Accept函数类似。在这个地方等待执行,如果没有新的消息,这个函数就不会执行下一句,一直等待。 2:接收的是字节流,需要转化成字符串 3:判断远程关闭联接的方式 4:如果对方的消息非常大,还得循环接收这个data。 4:如何管理这些联接(thread) 通过上边的程序,基本上可以建立一个侦听,并且处理联接会话。但是如何管理这些thread呢?不然大量产生thread可是一个灾难。 管理的方法比较简单,在Listener里面我定义了一个静态的哈希表(static public Hashtable Connections=new Hashtable();),存储Connection实例和它对应的Thread实例。而connection中也加入了一个最后联接时间的定义(private DateTime _lastConnectTime;)。在新链接建立的时候(Listener的Accept()之后)就把Connection实例和Thread实例存到哈希表中;在Connection的Receive的时候修改最后联接时间。这样我们就可以知道该Connection在哪里,并且会话是否活跃。 然后在Winform程序里头可以管理这些会话了,设置设置超时。 在网络环境下,我们最感兴趣的两个命名空间是和 s。命名空间通常与较高程的操作有关,例如download或upload,试用HTTP和其他协议进行Web请求等等,而s命名空间所包含的类通常与较低程的操作有关。如果要直接使用Sockets或者 TCP/IP之类的协议,这个命名空间的类是非常有用的。 在.Net中,s 命名空间为需要严密控制网络访问的开发人员提供了 Windows Sockets (Winsock) 接口的托管实现。 命名空间中的所有其他网络访问类都建立在该套接字Socket实现之上,如TCPClient、TCPListener 和 UDPClient 类封装有关创建到 Internet 的 TCP 和 UDP 连接的详细信息;NetworkStream类则提供用于网络访问的基础数据流等,常见的许多Internet服务都可以见到Socket的踪影,如 Telnet、Http、Email、Echo等,这些服务尽管通讯协议Protocol的定义不同,但是其基础的传输都是采用的Socket。 其实,Socket可以象流Stream一样被视为一个数据通道,这个通道架设在应用程序端(客户端)和远程服务器端之间,而后,数据的读取(接收)和写入(发送)均针对这个通道来进行。 可见,在应用程序端或者服务器端创建了Socket对象之后,就可以使用Send/SentTo方法将数据发送到连接的Socket,或者使用Receive/ReceiveFrom方法接收来自连接Socket的数据。 针对Socket编程,.NET 框架的 Socket 类是 Winsock32 API 提供的套接字服务的托管代码版本。其中为实现网络编程提供了大量的方法,大多数情况下,Socket 类方法只是将数据封送到它们的本机 Win32 副本中并处理任何必要的安全检查。如果你熟悉Winsock API函数,那么用Socket类编写网络程序会非常容易,当然,如果你不曾接触过,也不会太困难,跟随下面的解说,你会发觉使用Socket类开发 windows 网络应用程序原来有规可寻,它们在大多数情况下遵循大致相同的步骤。 在使用之前,你需要首先创建Socket对象的实例,这可以通过Socket类的构造方法来实现: public Socket(AddressFamily addressFamily,SocketType socketType,ProtocolType protocolType); 其中,addressFamily 参数指定 Socket 使用的寻址方案,socketType 参数指定 Socket 的类file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] 型,protocolType 参数指定 Socket 使用的协议。 下面的示例语句创建一个 Socket,它可用于在基于 TCP/IP 的网络(如 Internet)上通讯。 Socket temp = new Socket(etwork, , ); 若要使用 UDP 而不是 TCP,需要更改协议类型,如下面的示例所示: Socket temp = new Socket(etwork, , ); 一旦创建 Socket,在客户端,你将可以通过Connect方法连接到指定的服务器,并通过Send/SendTo方法向远程服务器发送数据,而后可以通过 Receive/ReceiveFrom从服务端接收数据;而在服务器端,你需要使用Bind方法绑定所指定的接口使Socket与一个本地终结点相联,并通过Listen方法侦听该接口上的请求,当侦听到用户端的连接时,调用Accept完成连接的操作,创建新的Socket以处理传入的连接请求。使用完 Socket 后,记住使用 Shutdown 方法禁用 Socket,并使用 Close 方法关闭 Socket。 可以看出,以上许多方法包含EndPoint类型的参数,在Internet中,TCP/IP 使用一个网络地址和一个服务端口号来唯一标识设备。网络地址标识网络上的特定设备;端口号标识要连接到的该设备上的特定服务。网络地址和服务端口的组合称为终结点,在 .NET 框架中正是由 EndPoint 类表示这个终结点,它提供表示网络资源或服务的抽象,用以标志网络地址等信息。.Net同时也为每个受支持的地址族定义了 EndPoint 的子代;对于 IP 地址族,该类为 IPEndPoint。IPEndPoint 类包含应用程序连接到主机上的服务所需的主机和端口信息,通过组合服务的主机IP地址和端口号,IPEndPoint 类形成到服务的连接点。 用到IPEndPoint类的时候就不可避免地涉及到计算机IP地址,命名空间中有两种类可以得到IP地址实例: IPAddress类:IPAddress 类包含计算机在 IP 网络上的地址。其Parse方法可将 IP 地址字符串转换为 IPAddress 实例。下面的语句创建一个 IPAddress 实例: IPAddress myIP = ("192.168.0.1"); Dns 类:向使用 TCP/IP Internet 服务的应用程序提供域名服务。其Resolve 方法查询 DNS 服务器以将用户友好的域名(如"")映射到数字形式的 Internet 地址(如 192.168.0.1)。Resolve方法 返回一个 IPHostEnty 实例,该实例包含所请求名称的地址和别名的列表。大多数情况下,可以使用 AddressList 数组中返回的第一个地址。下面的代码获取一个 IPAddress 实例,该实例包含服务器 的 IP 地址。 IPHostEntry ipHostInfo = e(" "); IPAddress ipAddress = sList[0]; 你也可以使用GetHostName方法得到IPHostEntry实例: IPHosntEntry hostInfo=tByName(" ") 在使用以上方法时,你将可能需要处理以下几种异常: SocketException异常:访问Socket时操作系统发生错误引发 ArgumentNullException异常:参数为空引用引发 ObjectDisposedException异常:Socket已经关闭引发 在掌握上面得知识后,下面的代码将该服务器主机( file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] 的 IP 地址与端口号组合,以便为连接创建远程终结点: IPEndPoint ipe = new IPEndPoint(ipAddress,11000); 确定了远程设备的地址并选择了用于连接的端口后,应用程序可以尝试建立与远程设备的连接。下面的示例使用现有的 IPEndPoint 实例与远程设备连接,并捕获可能引发的异常: */try { t(ipe);//尝试连接 } //处理参数为空引用异常 catch(ArgumentNullException ae) { ine("ArgumentNullException : {0}", ng()); } //处理操作系统异常 catch(SocketException se) { ine("SocketException : {0}", ng()); } /* 需要知道的是:Socket 类支持两种基本模式:同步和异步。其区别在于:在同步模式中,对执行网络操作的函数(如 Send 和 Receive)的调用一直等到操作完成后才将控制返回给调用程序。在异步模式中,这些调用立即返回。 综合运用以上阐述的使用Visual C#进行Socket网络程序开发的知识,下面的程序是一个简单的Socket通讯实例,client向server发送一段测试字符串,server接收并显示出来,给予client成功相应。 *///client端 using System; using ; using ; using ; using s; namespace socketsample { class Class1 { static void Main() { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = (host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket c = new Socket(etwork, , ); t(ipe); string sendStr = "hello!This is a socket test"; byte[] bs = file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53] es(sendStr); (bs, , 0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = e(recvBytes, , 0); recvStr += ing(recvBytes, 0, bytes); ine(recvStr); (); } catch (ArgumentNullException e) { ine("ArgumentNullException: {0}", e); } catch (SocketException e) { ine("SocketException: {0}", e); } ne(); } } } //server端using System; using ; using ; using ;using s; namespace Project1 { class Class2 { static void Main() { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = (host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket s = new Socket(etwork, , ); (ipe); (0); Socket temp = (); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; file:///C|/Documents and Settings/ITboy/桌面/新建文件夹 (2)/C_Socket网络编程.txt[2010-4-23 0:33:53]
版权声明:本文标题:C_Socket网络编程 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1703200725h442011.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论