计算机实验代码 42页

  • 77.23 KB
  • 2022-08-30 发布

计算机实验代码

  • 42页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档由用户上传,淘文库整理发布,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,请立即联系网站客服。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细阅读内容确认后进行付费下载。
  4. 网站客服QQ:403074932
用WINSOCK控件编写聊天程序在工具箱中增加Winsock控件,选中“MicrosoftWinsockControl6.0”1、设计Tcp服务器程序在窗体中加入一个Winsock控件,取名WinsockfwqTxtfs(发送)文本框Txtjs(接收)文本框Cmdexit(退出)按钮PrivateSubCmdexit_click()EndEndSndPrivateSubForm_Load()Txtfs.Visible=FalseTxtjs.Visible=FalseWinsockfwq.LocalPort=1001Winsockfwq.ListenEndSubPrivateSubTxtfs_Change()Winsockfwq.sendDataTxtfs.TextEndSubPrivateSubWinsockfwq_Close()Winsockfwq.CloseEndEndSubPrivateSubWinsockfwq_ConnectionRequest(ByvalrequestldAsLong)Txtfs.Visible=TrueTxtjs.Visible=TrueIfWinsockfwq.StateoSckclosedThenWinsockfwq.closeWinsockfwq.AcceptrequestedEndSubPrivateSubWinsockfwq_DataArrival(ByvalbytesTotalAsLong)DimtmPstrAsStringWinsockfwq.GetDatatmPstrTxtjs.Text=tmPstrEndSub2、设计Tcp客户端程序在窗体中加入Winsock,取名为WinsockkhdTxtzjm(主机名)文本框Txtfs(发送)文本框Txtjs(接收)文本框Cmdexit(退出)按钮Cmdlj(连接)按钮\nPrivateSubCmdlj_Click()Winsockkhd.ConnectEndSubPrivateSubCmdexit_Click()EndEndSubPrivateSubForm_Load()Txtfs.Visble=FalseTxtjs.Visible=FalseWinsockkhd.RemotePort=1001Winsockkhd.RemoteHost=”90.0.0.50”EndSubPrivateSubTxtzjm_Change()Winsockkhd.RemoteHost=Txtzjm.TextEndSubPrivateSubTxtfs_Change()Winsockkhd.SendDataTxtfs.TextEndSubPrivateSubWinsockkhd_Close()Winsockkhd.CloseEndEndSubPrivateSubWinsockkhd_DataArrval(ByvalbytesTotalAsLong)DimtmPstrAsStringWinsockkhd.GetDatatmPstrTxtjs.Text=tmPstrEndSubOptionExplicitPrivateIgnoreTextAsBoolean*各控件说明■名称类型作用•frmMainFormCHAT主窗体'WinsocklWinsock连接控件*Label1LabelCONNECTWITHIP标签\n*Label2LabelLOCALPORT标签*Label3LabelREMOTEPORT标签'txtRemotelPTextBox远程IP地址输入框'txtLocalPortTextBox本地PORT输入框'txtRemotePortTextBox远程PORT输入框'cmdConnectCommandButton连接CONNECT按钮'Label4LabelTypeyourtextandhitEntertosendit.标签'Framel(remoteip)FrameREMOTEIP框架'Frame2(hostip)FrameHOSTIP框架*Text1TextBox显示对方(远程主机)发送的CHAT内容'Text2TextBox输入己方(本地主机)要发送的CHAT内容,按ENTER键发送'cmdClearCommandButton清空输入框(TEXT2)和显示框(TEXT1)中的内容'StatusBarlStatusBar状态栏'当CLEAR按钮按下时,清空TEXT1和TEXT2中的内容PrivateSubcmdClear_Click()Textl=“”WithText2'清空输入框.Text=””'并把焦点置于TEXT2.SetFocusEndWithEndSub当CONNECT按钮按下时,进行以下操作PrivateSubcmdConnect_Click()OnErrorGoToErrHandlerWithWinsockl'设置RemoteHost屈性.RemoteHost=Trim(txtRemotelP)'设置RemotePort属性'RemotePort属性的值应该等于远程主机上的LocalHost展性的值.RemotePort=Trim(txtRemotePort)•LocalPort属性的值是不能改变的,必须检查它是否己经被设置'如果LocalPort屈性为空(没有被设置),将其设为在LocalPort输入框中输入的数值If.LocalPort=EmptyThen.LocalPort=Trim(txtLocalPort)Frame2.Caption二丄ocallP\n'这是必须的,Bind方法的作用是为控件“保留”一个本地端口,防止被其他用户调用。.Bind.LocalPortEndIfEndWith'为了保证使用者不能改变LocalPort的值,将txtLocalPort输入框锁定txtLocalPort.Locked=True'在状态栏中显示“正在连接”的状态StatusBarl.Panels(1).Text="正在连接”&Winsockl.RemoteHost&””'如果连接正常,做以下设置Framel・Enabled=TrueFrame2.Enabled=TrueLabeW.Visible=TrueText2.SetFocusExitSub'如果在连接过程中出现错误,则转向ErrHandler:,并显示错误提示ErrHandler:MsgBox”连接远程主机失败!",vbCriticalEndSub'当窗体加载时显示提示信息并在txtRemotelP框中显示本地主机的IPPrivateSubForm_Load()ShowtxtRemotelP=Winsockl丄ocallPEndSubPrivateSubLabel5_Click()EndSub,接收TEXT2输入框的按键,并做响应PrivateSubText2_KeyPress(KeyAsciiAsInteger)'定义变量Last_Line_Feed来记录最后输入行的位置StaticLast_Line_FeedAsLong'定义New_Line字符串记录新键入的一行文本的内容DimNew_LineAsString'如果使用者按下CLEAR按钮对输入框内容清空,这时TEXT2为空,则重设最后输入行的位置为0IfTrim(Text2)=vbNullStringThenLast_Line_Feed=0'当使用者按下ENTER键时IfKeyAscii=13Then\n'取得最后输入行的内容并赋值给New_Line字符串New_Line=Mid(Text2,Last_Line_Feed+1)'重设最后输入行的位置Last_Line_Feed=Text2.SelStart,通过WINSOCK发送新输入的一行文本的内容Winsockl.SendDataNew_Line'在状态栏显示发送信息StatusBarl.Panels⑵.Text="发送"&(LenB(New_Line)/2)&"字节”EndIfEndSubPrivateSubtxtRemotelP_Change()EndSub当WINSOCK接收到新的数据(信息)时,进行以下响应PrivateSubWinsockl_DataArrival(ByValbytesTotalAsLong)'定义New_Text字符串来记录新接收的信息DimNew_TextAsString'接收信息并赋值给New_TextWinsockl.GetDataNew_Text'在TEXT1显示框中显示新接收到的信息Textl.SelText=New_TextFramel.Caption=Winsockl.RemoteHostIP'在状态栏中显示接收信息StatusBarl.Panels(2).Text=u接收到”&bytesTotal&“字节”EndSub用VB实现聊天讨论室和点对点会话在一个单位内部或通过广域协议(如X.25)互联的行业内部都有几十或上万台计算机互联,用Intranet虽然可以建立聊天室,但实现点对点实时对话却比较困难。木人用Winsock和VB口制了一套聊天室和对话系统,特京来供同行们参考。—Winsock的主耍属性、事件和方法Winsock是不可见控件,控件文件名是MSWINSCK.OCX,全称Mcirosoftwinsockcontrol,使用时耍将此控件调入工具箱。1•属性:①Protocol〃使用TCP协议;②RemoteHost//准备连接远程机的IP地址\n②RemotePort//连接远程机的IP端口号(1024—65535之间)③LocalPort//*地机监听IP端口号必须与呼叫机端口号相同2•方法:©connect//中请连接远程机②listen//设置监听③accept//建立实际连接④senddata〃发送数据©getdata〃接收数据©close//关闭连接3•事件:®connectionrequest//一方请求连接时另一方产生②connect〃一方机接受连接时另一方产生③close//—方机关闭连接时另一方产生©dataArrival〃一方发送数据另一方产生⑤error//请求连接失败时产生二•制作方法⑴在一工程中添加两个表单forml(模拟客户端)、form2(模拟服务器端)。forml中装入控件:控件名主耍属性用途\nVB.Formformlcaption』雷萌聊天室”controlbox=0'False模拟客户机表单VB.Textboxtextlmultiline=-1'Truescrollbars=3Bath用于输入发往聊天室的信息VB.Textboxtext2locked=-1Truemultiline=-1'Truescrollbars=3Bath显示从聊天室发来的信息VB.Comboboxcomboltext二”10.84.234.11”'任定默认地址放入常用的地址VB.Commandbuttoncommlcaption』退出”最小化formlVB.Commandbuttoncomm2caption』连接”请求与输入的地址连接VB.Commandbuttonsendcaption』发送”发送Text1中的内容VB.Labellabehcaption=“请在此输入发表的信息”\nTextl的框标VB.LabelIabel2caption=,s聊天室或对方的信息”Text2的框标VB.LabelIabel3caption』等待连接”显示连接状态信息VB.LabelIabel4caption=^^聊天室或对方地址”用于指示CombolVB.LabelIabel5caption』操作选地址连接,连接成功看到聊天室内容后再输信息发送”操作说明VB.Timertimerlinterval=6000;enabled=false防止连接超时MSWinsocklib.winsocka用丁•数据传输form2中装入控件:控件名主耍属性用途\nVB.Formform2caption』接收信息”controlbox=0'False模拟客户机表单VB.Commandbuttoncommand1caption=”返回”隐含Form2窗口VB.Commandbuttoncommand2caption』对话”点对点会话时用此直接启动FormlVB.Textboxtextl\nIocked=-1'Truemultiline=-1'Truescrollbars=3'Bath存放聊天或对话内容VB.Labellabehcaption』接收的信息”Textl的框标MSWinsocklib.Winsocka用于监听MSWinsocklib.Winsockb用于传送聊天信息⑵在Forml的各控件事件中加入如下代码:DimflagAsBoolean注释:连接状态变量PrivateSuba_Connect()flag=True\nDimiAsStringa.GetDataiLabel3.Caption="连接成功!"Comm2.MousePointer=0Forml.MousePointer=0Timer1・Enabled=FalseIfi=Chr(O)ThenText2.Text=”你是今天第一个进入木聊天室的客户。”+Chr(13)+Chr(10)ElseText2.Text=Text2.Text+iEndIfText2.SelStart=Len(Text2.Text)Send.MousePointer=0Combol・Enabled=FalseComm2.Caption二11断开连接”\nTextl.SetFocus\nEndSubPrivateSuba_Error(ByValNumberAsInteger,DescriptionAsString,ByVaiScodeAsLong,ByVaiSourceAsString,ByVaiHelpFileAsString,ByVaiHelpContextAsLong,CancelDisplayAsBoolean)flag=FalseTimer1・Enabled=FalseComm2.MousePointer=0Forml.MousePointer=0MsgBox"网络连接失败!”Label3.Caption=”等待连接”Combol・Enabled=TrueCombo1.SetFocusa.CloseComm2.Caption="连接"EndSubPrivateSubComm1_Click()a.Close注释:关闭连接Forml.WindowState=1\nPrivateSubComm2_Click()IfComm2.C即tion="断开连接"Thena.OloseComm2.Caption="连接"Label3.Caption="等待连接”Combol・Enabled=TrueTimerl.Enabled=FalseComm2.MousePointer=0Forml.MousePointer=0ElseText2.Text="”Label3.Caption="正在连接Comm2.MousePointer=11Forml.MousePointer=11Timerl.Enabled=Trueflag=Falsea.Protocol=sckTCPProtocola.RemoteHost=Combol.Texta.RemotePort=3000a.ConnectEndSub\nPrivateSubForm_DblClick()IfMsgBoxf1关闭本聊夭室!确认吗?36,”退出系统=6ThenEndElseForml.WindowState=1EndIfEndSubPrivateSubForm_Load()IfApp.PrevInstaneeThenMsgBox•'本系统己经加载,请看任务拦!”,48,”提示”EndEndIfflag=FalseLoadForm2"读入form2进入监听EndSubPrivateSubSend_Click()DimSAsStringOnErrorGoToffff'防止链路中断Send.MousePointer=11\nIfRight(Text1.Text,1)<>Chr(10)ThenS=Textl.Text+Chr(13)+Chr(10)ElseS=Textl.TextEndIfIfflagThena.SendDataSEndIfExitSubffff:MsgBox”连接中断!”,48,”提示”a.CloseSend.MousePointer=0Comm2.Caption="连接"Label3.Caption="等待连接”Combol.Enabled=TrueComm2.MousePointer=0Forml.MousePointer=0ExitSubPrivateSubTimer1_Timer()\nflag=FalseTimerl.Enabled=FalseComm2.MousePointer=0Forml.MousePointer=0MsgBox*'网络连接失败(超时)!”Label3.Caption="等待连接”Combol・Enabled=TrueCombo1.SetFocusa.CloseComm2.Caption="连接”EndSub⑶在Form2的各控件事件中加入如下代码:Constmaxn=200'最人同时连接本机的客户数Dimuser(maxn)AsBooleanPrivateSubCommand1_Click()Form2.HideEndSubPrivateSubCommand2_Click()LoadForml\nForml.ShowEndSubPrivateSubForm_Load()Dimstr1AsStringForm2.Caption="雷萌通信软件"注释:winsock控件a作为服务器程序监听a.LocalPort=3000a.ListenEndSubPrivateSuba_ConnectionRequest(ByValrequestIDAsLong)DimiAsLongFori=1Tomaxn,当一客户请求时给启动一Winsock控件标志号IfNotuser(i)Thenuser(i)=TrueExitForEndIfNextiIfi>maxnThenExitSubEndIf\nLoadb(i)'当一•客户请求时启动一Winsock控件b(i).AcceptrequestID注释:实际建立连接IfTextl.Text=Then注释:发送数据b(i).SendDataChr(O)Elseb(i).SendDataTextl.TextEndIfForm2.ShowEndSubPrivateSubs_Close(lndexAsInteger)b(lndex).CIose注释:关闭连接Unloadb(lndex)注释:卸载—个WinSock控件user(lndex)=FalseEndSubPrivateSubb_DataArrival(lndexAsInteger,ByVaibytesTotalAsLong)DimstrAsStringDimiAsLongb(lndex).GetDatastrTextl.Text=Textl.Text+strFori=1TomaxnIfuser(i)Then\nb(i).SendDatastrEndIfNextiEndSub1.1系统整体流程\nVB利用UDP制作简单的点对点聊天程序收藏VERSION5.00Object=M{248DD890-BB45-11CF-9ABC-0080C7E7B78D}#1.0#0°;“MSWINSCK.OCX”BeginVB.FormfrmMainBorderStyle=1'FixedSingleCaption=“点对点聊天“ClientHeight=5175ClientLeft=45ClientTop=360Clientwidth=6720KeyPreview=・1'TrueLinkTopic="Forml"LockControls=-1'TrueMaxButton=0FalseScaleHeight=5175ScaleWidth=6720StartUpPosition=2,屏幕中心BeginVB.TimertimerCheckConnectEnabled=0'FalseInterval=10000Left=2160Top=4560EndBeginVB.TextBoxtextSendHeight=1455Left=120MultiLineScrollBarsTabindexTopWidth=-1'True=2'Vertical=4=3000=6495EndBeginVB.CommandButtoncmdConnectCaption二”连接(&C)”Default=・1TrueHeightLeftTabindexTopWidth=37556402EndBeginVB.TextBoxtextPortHeight=270Left=4440\nTabindex=1Text二”5300“Top=200Width=855EndBeginMSWinsockLib.WinsockwskLeft=1320Top=4680_ExtentX=741_ExtentY=741_Version=393216EndBeginVB.CommandButtoncmdExitCancel=-1'TrueCaption=”退出(&X)”Height=375Left=5640Tabindex=6Top=4640Width=975EndBeginVB.CommandButtoncmdSendCaption=”发送(&S)”Height=375Lzeft=4680Tabindex=5Top=4640Width=975EndBeginVB.TextBoxtextAddressHeight=270Left=1440Tabindex=0Top=200Width=1695EndBeginVB.TextBoxtextMessageHeight=2175Left=120MultiLine=・1TrueScrollBars=2'VerticalTabindex=3Top=680Width=6495\nEndBeginVB.LabelLabel1CaptionHeightLeftTabindex”输入聊天端口叮25532408TopWidthEndBeginVB.LabelIMsg2401215CaptionHeightLeftTabindexTopWidth八输入聊天的IP:n25512072401335EndEndAttributeVB_Name=nfrmMainHAttributeVB_GlobalNameSpace=FalseAttributeVB.Creatable=FalseAttributeVB_PredeclaredId=TrueAttributeVB_Exposed=False'发送消息函数PrivateDeclareFunctionSendMessageLibHuser32,fAliasMSendMessageAH(ByVaihwndAsLong,ByVaiwMsgAsLong,ByVaiwParamAsLong,IParamAsAny)AsLong,使滚动条自动下拉PrivateConstWM_VSCROLL=&Hl15PrivateConstSB_BOTTOM=7'标识对方是否在线PrivateisOnlineAsBoolean,动画窗体(使指定窗体闪动好提示对方有消息来了)PrivateDeclareFunctionFlashWindowLibHuser32n(ByVaihwndAsLong,ByVaiblnvertAsLong)AsLong'验证IP的合法性PrivateDeclareFunctioninet.addrLibnws2_32.dHu(ByVaicpAsString)AsLong'显示XP风格函数PrivateDeclareSubInitCommonControlsLibHcomctl32.dllu()PrivateSubForm_Initialize()1显示XP风格InitCommonControlsEndSub\nPrivateSubcmdConnect_Click()'IP地址不能为空IftextAddress.Text=”"ThenMsgBox”请输入对方的IP地址或者计算机名!!n,vbCritical,”错误“textAddress.SetFocusExitSubElse'当是以IP地址连接方式下IfInStr(textAddress.Text,Then,当IP地址不合法Ifinet_addr(textAddress.Text)=-1ThenMsgBox”请检査你的IP合法性!!u,vbCritical,”提示“'选择输入的字符串textAddress.SelStart=0textAddress.SelLength=Len(textAddress.Text)textAddress.SetFocusExitSubEndIfEndIfEndIf'端口不能为空IftexlPort.Text=n"ThenMsgBox”请输入聊天的端口号!!",vbCritical,”错误“textPort.SetFocusExitSubElse'端口必须是数字IfNotIsNumeric(textPort.Text)ThenMsgBox”请输入1-65536之间的数字!!\vbCritical,°错误”'选择输入的字符串textPort.SelStart=0textPort.SelLength=Len(textPort.Text)textPort.SetFocusExitSubElse'对数字进行验证IfCLng(textPort.Text)<1AndCLng(textPort.Text)>65536ThenMsgBox”请输入1-65536之间的数字!!”,vbCritical,“错误”textPort.SetFocusExitSubEndIfEndIfEndIf'连接对方发送在线消息(在连接前先断开连接)wsk.CIose\n'指明自己的连接端口wsk.LocalPort=textPort.Text'对方的连接端口wsk.RemotePort=textPort.Text'对方的IP或者计算机名wsk.RemoteHost=textAddress-Textwsk.Bind'发送在线消息wsk.SendData"Online**A_A**n&wsk.LocallP'禁用连接按钮和IP地址栏以及端口textAddress.Enabled=FalsetextPort.Enabled=FalsecmdConnect.Enabled=FalsetimerCheckConnect.Enabled=TrueEndSubPrivateSubcmdExit_Click()UnloadMeEndSubPublicSubcmdSend_Click()DimstrSendAsString'发送消息给对方IftextSend.Text<>',uThen,验证IP和端口IftextAddress.Text<>H,'AndtextPort.Text<>""Then'判断是否在线IfisOnlineThenstrSend=ReplaceExceptiveString(textSend.Text)wsk.SendDatastrSend&"**人_八**”&wsk.LocallPtextMessage.Text=textMessage.Text&vbNewLine&wsk.LocallP&""&Format(Now,"yyyy年-mm月-dd日HH:MM:SS")&vbNewLine&textSend.TexttextSend.Text=vbNullStringSendMessagetextMessage.hwnd,WM_VSCROLL,SB_BOTTOM,0Else'如果不在线恢复可用连接状态MsgBox”对方不在线上!!“,vbCritical,”提示“cmdConnect.Enabled=TruetextAddress.Enabled=TruetextPort.Enabled=TrueEndIfElse\nMsgBox”请检查IP地址和端口号是否合法!!蔦vbCriticalJ提示”'ExitSubEndIfEndIfEndSub'替换特殊字符串函数PrivateFunctionReplaceExceptiveString(ByValstrCheckAsString)AsString'这里替换的字符我用chr(O)因为正常是输入不了这个字符的IfLeft(strCheck,13)二"Online**"/**"ThenReplaceExceptiveString=String(&Chr(O))&Mid(strCheck,14,Len(strCheck)・13)ElselfLeft(strCheck,15)=uOnlineOK**A_A**nThenReplaceExceptiveString=String(10,Chr(O))&Mid(strCheck,16,Len(strCheck)-15)ElselfLeft(strCheck,12)="Leave**A_A**"ThenReplaceExceptiveString=String(6,Chr(O))&Mid(strCheck,13,Len(strCheck)-12)ElseReplaceExceptiveString=strCheckEndIfEndFunction'还原特殊字符串甫数PrivateFunctionRestoreExceptiveString(ByValstrCheckAsString)AsStringIfLeft(strCheck,10)=Slring(10,Chr(O))ThenRestoreExceptiveString="OnlineOK**A_A**"&Mid(strCheck,11,Len(strCheck)-10)ElselfLeft(strCheck,8)=String(8,Chr(O))ThenRestoreExceptiveString="Online**A_A**"&Mid(strCheck,9,Len(strCheck)-8)ElselfLeft(strCheck,6)=String(6,Chr(O))ThenRestoreExceptiveString=MLeave**A_A**M&Mid(strCheck,7,Len(strCheck)-6)ElseRestoreExceptiveString=strCheckEndIfEndFunctionPrivateSubForm_Load()hHook=SetWindowsHookEx(WH_KEYBOARD,AddressOfKeyboardProc,App.hlnstance,App.ThreadID)'指定协议类型为UDPwsk.Protocol=sckUDPProtocol'锁住信息显示栏Me.textMessage.Locked=TrueEndSubPrivateSubForm_UnIoad(CancelAsInteger)UnhookWindowsHookExhHook\n'当退出程序发送离线消息OnErrorResumeNextwsk.SendData"Leave**A_A**n&wsk.LocalIPEndSub,检测对方是否在线PrivateSubtimerCheckConnect_Timer()IfNotisOnlineThenMsgBoxu对方不在线,或者是网络有问题!!\vbCritical,H错误“,恢复可连接状态textAddress.Enabled=TruetextPort.Enabled=TruecmdConnect.Enabled=TruetimerCheckConnect.Enabled=FalseEndIfEndSub•Winsock消息接收事件PrivateSubwsk_DataArrival(ByValbytesTotalAsLong)'消息过滤DimstrMessageAsString,strArrayOAsStringOnErrorResumeNext'接收类型为字符串wsk.GetDatastrMessage,vbString'格式化字符串(自定义协议的时候可以根据自己的爱好,但是在分割字符串的符号上最好是不要太容易重复的标识以防消息判断错误)strArray=Split(strMessage,"**A_A**")'如果是上线消息IfLeft(strMessage,13)="Online*"—"*"ThenIftextMessage.Textv>""ThentextMessage.Text=textMessage.Text&vbNewLine&strAnay(1)&”在"&Format(Now,"yyyy年・mm月・dd日HH:MM:SS”)&“上线了!!“&vbNewLineElsetextMessage.Text=strArray(1)&"在"&Format(Now,"yyyy年-mm月-dd日HH:MM:SS”)&”上线了!!”&vbNewLineEndIf'给对方发送你已经在线了wsk.SendDataHOnlineOK**A_A**"&wsk.LocallP'设置处于上线状态isOnline=True\n'关闭检测在线记时器timerCheckConnect.Enabled=False'自动下来滚动条SendMessagetextMessage.hwnd,WM_VSCROLL,SB_BOTTOM,0'扇动窗体好知道有消息来了FlashWindowMe.hvvnd,1'禁用连接按钮和IP地址栏以及端口textAddress.Enabled=FalsetextPort.Enabled=FalsecmdConnect.Enabled=False'接收到对方已经在线了ElselfLeft(strMessage,15)="OnlineOK**A_A**"Then,显示对方已经在线了IftextMessage.Text<>"”ThentextMessage.Text=textMessage.Text&vbNewLine&strAnay(1)&”在"&Format(Now,"yyyy年・mm月-ddHHH:MM:SS”)&“上线了!!“&vbNewLineElsetextMessage.Text=strArray(1)&"在"&Format(Now,"yyyy年-mm月-dd日HH:MM:SS”)&“上线了!!”&vbNewLineEndIf'设置任线标识isOnline=True'关闭检测在线记时器timerCheckConnect.Enabled=False'自动下来滚动条SendMessagetextMessage.hwnd,WM_VSCROLL,SB_BOTTOM,0'扇动窗体好知道有消息来了FlashWindowMe.hwnd,1'禁用连接按钮和IP地址栏以及端口textAddress.Enabled=FalsetextPort.Enabled=FalsecmdConnect.Enabled=FalseElselfLeft(strMessage,12)="Leave**A_A**"Then'当对方离线了IftextMessage.Text<>u"ThentextMessage.Text=textMessage.Text&vbNewLine&strArray(1)&”在"&Format(Now,"yyyy年-mm月-dd日HH:MM:SSU)&"离线了!!"&vbNewLineElsetextMessage.Text=strArray(1)&"在"&Format(Now,"yyyy年-mm月-dd日HH:MM:SS”)&“离线了!!”&vbNewLineEndIf\n'设置离线标识isOnline=False'恢复对连接状态textAddress.Enabled=TruetextPort.Enabled=TruecmdConnect.Enabled=True'自动下来滚动条SendMessagetextMessage.hwnd,WM_VSCROLL,SB_BOTTOM,0'扇动窗体好知道有消息来了FlashWindowMe.hwnd,1Else般聊天内容textMessage.Text=textMessage.Text&vbNewLine&strArray(l)&""&Format(Now,"yyyy年-mmM-dd日HH:MM:SS")&vbNewLine&RestoreExceptiveString(strArray(0))&vbNewLine'自动下来滚动条SendMessagetextMessage.hwnd,WM_VSCROLL,SB_BOTTOM,0'扇动窗体好知道有消息来了FlashWindowMe.hwnd,1EndIfEndSubPrivateSubwsk_Error(ByValNumberAsInteger,DescriptionAsString,ByVaiScodeAsLong,ByVaiSourceAsString,ByVaiHelpFileAsString,ByVaiHelpContextAsLong,CancelDisplayAsBoolean)'当有错误产生显示错误信息MsgBoxDescription“恢复可连接状态textAddress.Enabled=TruetextPort.Enabled=TruecmdConnect.Enabled=TrueEndSubAttributeVB_Name=umodKeyBoardMOptionExplicitPrivateConstWM.KEYDOWN=&Hl0()PrivateConstWM.KEYUP二&H101PrivateConstWM_SYSKEYDOWN二&H104PrivateConstWM.SYSKEYUP二&H105PublicConstWH.KEYBOARD=2PrivateConstVK.CONTROL二&H11\nDeclareFunctionCallNextHookExLibnuser32n(ByVaihHookAsLong,ByVaincodeAsLong,ByVaiwParamAsLong,IParamAsAny)AsLongDeclareFunctionGetKeyStateLibMuser32n(ByVainVirtKeyAsLong)AsIntegerDeclareFunctionSetWindowsHookExLibMuser32HAlias"SetWindowsHookExAM(ByVaiidHookAsLong,ByVailpfnAsLong,ByVaihmodAsLong,ByVaidwThreadldAsLong)AsLongDeclareFunctionUnhookWindowsHookExLibnuser32H(ByVaihHookAsLong)AsLongPublichHookAsLongPublicFunctionKeyboardProc(ByValidHookAsLong,ByVaiwParamAsLong,ByVai1ParamAsLong)AsLongIfidHook<0ThenKeyboardProc=CallNextHookEx(hHook,idHook,wParam,ByVaiIParam)ElseIf(GetKeyState(VK_CONTROL)And&H8000)AndwParam=13ThenIffnnMain.textSend.Text<>""ThenfnTiMain.cnidSend_ClickKeyboardProc=1ExitFunctionEndIfKeyboardProc=CallNextHookEx(hHook,idHook,wParam,ByVaiIParam)EndIfEndFunction本文来自CSDN博客,转载请标明出处:httD:〃blog.csdn.net/chenhui530/a「chive/2007/10/01/1809130.aspx\n1•属性:①Protocol^)//使用TCP协议;②RemoteHost//准备连接远程机的IP地址③RemotePort//连接远程机的IP端口号(1024—65535Z间)④LocalPort//^地机监听IP端口号必须与呼叫机端口号相同2•方法:©connect//屮请连接远程机②listen//设置监听③accept//建立实际连接④senddata//发送数据⑤gctdata//接收数据⑥close//关闭连接3•事件:©connectionrequest//—方请求连接时另一方产生©connect//一方机接受连接时另一方产生③close//—方机关闭连接时另一方产生④dataArrival//一方发送数据另一方产生©error//请求连接失败时产生二•制作方法⑴在一工程中添加两个农单forml(模拟客户端)、form2(模拟服务器端)。forml中装入控件:控件名主要屈性用途VB.Formformlcaption二"雷萌聊天室"controlbox=OwFalse模拟客户机表单\nVB.Tcxtboxtcxtlmultiline1'Truescrollbars=3'Bath用于输入发往聊夭室的信息VB.Textboxtext2locked—TTruemultiline1'Truescrollbars=34Bath显示从聊天室发来的信息VB.Comboboxcombo1texU'10.84.234.11”'任定默认地址放入常用的地址VB.CommandbuttoncommIcaption-'退出”最小化formlVB.Conimandbuttoncomm2caption^*连接"请求与输入的地址连接VB.Conimandbuttonsendcaplion="发送"发送Textl中的内容VB.Labcllabcllcaption=<储在此输入发表的信息”Textl的框标VB.LabelIabel2caption二“聊天室或对方的信息”Text2的框标VB.Labellabel3caption二”等待连接”显示连接状态信息VB.LabellabeUcaption-'聊夭室或对方地址"用于指示Combo1\nVB.Labellabel5caption=5«作:选地址连接,连接成功看到聊夭室内容后再输信息发送”操作说明VB.Timertimer1interval=6000;enabled=false防止连接超时MSWinsocklib.winsocka用于数据传输form2中装入控件:控件名主要属性用途VB.Formform2caption-5^收信息"controlbox=()4False模拟客户机表单VB.Conimandbuttoncomniand1caption=^^返回”隐含Form2窗口VB.Coniniandbuttoncommand2caplion="对话"点对点会话时用此直接启动Form1VB.Tcxtboxtcxtllocked=-1Truemuliiline=-rTruescrollbars二3'Bath存放聊天或对话内容VB.Labellabellcaption-^收的信息”Text!的框标\nMSWinsocklib.Winsocka用于监听MSWinsocklib.Winsockb用于传送聊夭信息⑵在Form1的各控件事件中加入如下代码:DimflagAsBoolcan注释:连接状态变吊PrivateSuba_Connect()flag二TrueEndSubPrivateSuba_DataArrival(ByValbytesTotalAsLong)DimiAsStringa.GetDataiLabel3.Caption="连接成功!”Comm2.MousePointer=0Forml.MousePointer=()Timer1.Enabled=FalseIfi=Chr(O)ThenText2.Text=H你是今天第一个进入本聊天室的客户「Chr(⑶Chr(10)\nElseTcxt2.Tcxt=Tcxt2.TcxtiEndlfText2.SelStart=Len(Text2.Text)Send.MousePointer=0ComboLEnabled=FalseComm2.Caption="断开连接"Textl.SetFocusEndSubPrivateSuba_Error(ByValNumberAsIntegenDescriptionAsString,ByValScodeAsLong,ByValSourceAsString,ByValHe]pFileAsSlring,ByValHelpContextAsLong,CancelDisplayAsBoolean)flag二FalseTimer1.Enabled=FalseComm2.MousePointer=0Forml.MousePointer=0MsgBox"网络连接失败!"Label3.Caption二"等待连接”Combo1.Enabled=TrueCombol.SetFocusa.CloseComm2.Caption=,r连接"\nPrivateSubComml_Click()a.Close注释:关闭连接Forml.WindowState=1EndSubPrivateSubComm2_Click()IfComm2.Caption="断开连接"Thena.CloseComm2.Caption=H连接"Label3.Caption=u等待连接”Combo1・Enabled=TrueTimer1.Enabled二FalseComm2.MousePointer=0Forml.MousePointer=()ElseTexl2.Texl=””Label3.Caption="正在连接Comm2.MousePointer=l1Forml.MousePointer=11Timer1.Enabled=Truefiag=Falsea.Protocol=sckTCPProtocol\na.RemoteHost=Combo1.Texta.RcmotcPort=3000a.ConnectEndlfEndSubPrivateSubForm_DblClick()IfMsgBoxC*关闭木聊天室!确认吗?”,36,”退出系统,,)=6ThenEndElseFormLWindowState=IEndlfEndSubPrivateSubForm_Load()IfApp.PrevInstanceThenMsgBox”木系统已经加载,请看任务拦!”,4&”提示”EndEndlfflag=FalseLoadFonn2,读入form2进入监听PrivateSubSend_Click()\nDimSAsStringOnErrorGoTofffr防止链路中断Send.MousePoinier=l1IfRight(Tcxt1.Text,1)<>Chr(10)ThcnS=Text1.TextChr(13)Chr(l0)ElseS=Textl.TextEndIfIfflagThcna.SendDataSEndlfExitSubffff:MsgBox”连接中断!”,4&”提示”a.CloseSend.MousePointer=()Comm2.Caption="连接"Label3.Caption="等待连接”Combol.Enablcd二TrueComm2.MousePointer=0Forml.MousePointer=()\nEndSubPrivateSubTinierl_Timer()flag=FalseTimer1.Enabled=FalseComm2.MousePoinier=0Forml.MouscPointcr=0MsgBox"网络连接失败(超时)!“Labcl3.Caption="等待连接”Combo1.Enabled二TrueCombol.SetFocusa.CloscComm2.Caplion="连接"EndSub⑶在Form2的各控件事件中加入如下代码:Constmaxn=200w最大同时连接木机的客户数Dimuser(maxn)AsBooleanPrivateSubCommandl_Click()Form2.HidePrivateSubCommand2_Click()\nLoadForm1Form1.ShowEndSubPrivateSubForm_Load()DimstrlAsStringForm2.Caption=,M^萌通信软件“注释:winsock控件a作为服务器程序监听a.LocalPort=3()()()a.ListenEndSubPrivateSuba_ConnectionRequest(ByValrequestIDAsLong)DimiAsLongFori=lTomax『当一客户请求时给启动一Winsock控件标志号IfNotuser(i)Thenuser(i)=TrueExitForEndIfNcxtilfi>maxnThenEndlf\nLoadb(i),当一客户诸求时启动一Winsock控件b(i).AcceptrequestlD注释:实际建立连接IfTextl.Text=""Then注释:发送数据b(i).ScndDataChr(O)Elseb(i).SendDataTextl.TextEndlfForm2.ShowEndSubPrivateSubs_Close(IndexAsInteger)b(Index).Close注释:关闭连接Unloadb(Index)注释:卸载一个WinSock控件user(Index)=FalseEndSubPrivateSubb_DataArrival(IndexAsIntegei;ByValbytesTotalAsLong)DimstrAsStringDimiAsLongb(Indcx).GctDatastrTextI.Text=Text1.TextstrFori=lTomaxnIfuser(i)Then\nb(i).SendDatastrEndlfNextiEndSub

相关文档