动网论坛,站长建站首选,国内使用量最多的论坛软件 动网论坛官方技术讨论区 站长工具 申请属于您自己的免费论坛
首页 | 新闻资讯 | 网站运营 | 网络编程 | 数据库 | 服务器 | 网页设计 | 图像媒体 | 网络应用 | 搜索优化 | 资源下载 | 动网主机 | DVBOX
    本站内  互联网 ASP论坛  ASP.Net论坛  PHP论坛
  
   .Net → 阅读文章

 一个SDK里做聊天室的例子

作者来源: 
阅读 1160 人次 , 2006-3-29 4:33:00 


option explicit on
option strict on

imports system
imports system.io
imports system.text
imports system.threading
imports system.net
imports system.net.sockets
imports system.drawing
imports system.windows.forms
imports microsoft.visualbasic



class app

'entry point which delegates to c-style main private function
public overloads shared sub main()
main(system.environment.getcommandlineargs())
end sub

' entry point
overloads public shared sub main(args() as string)
' if the args parse in known way then run the app
if parseargs(args) then
' create a custom talker object
dim talkerobj as new talker(endpoint, client)
' pass the object reference to a new form object
dim form as new talkform(talkerobj)
' start the talker "talking"
talkerobj.start()

' run the applications message pump
application.run(form)
end if
end sub 'main

' parsed argument storage
private shared endpoint as ipendpoint
private shared client as boolean


' parse command line arguments
private shared function parseargs(args() as string) as boolean
try
if args.length = 1 then
client = false
endpoint = new ipendpoint(ipaddress.any, 5150)
return true
end if
 
dim port as integer
select case char.toupper(args(1).tochararray()(1))
case "l"c
port = 5150
if args.length > 2 then
port = convert.toint32(args(2))
end if
endpoint = new ipendpoint(ipaddress.any, port)
client = false
case "c"c
port = 5150
dim address as string = "127.0.0.1"
client = true
if args.length > 2 then
address = args(2)
port = convert.toint32(args(3))
end if
endpoint = new ipendpoint(dns.resolve(address).addresslist(0), port)
case else
showusage()
return false
end select
catch
end try

return true
end function 'parseargs


' show sample usage
private shared sub showusage()
messagebox.show("wintalk [switch] [parameters...]" & controlchars.crlf & controlchars.crlf & _
" /l [port]" & controlchars.tab & controlchars.tab & "-- listens on a port. default: 5150" & controlchars.crlf & _
" /c [address] [port]" & controlchars.tab & "-- connects to an address and port." & controlchars.crlf & controlchars.crlf & _
"example server - " & controlchars.crlf & _
"wintalk /l" & controlchars.crlf & controlchars.crlf & _
"example client - " & controlchars.crlf & _
"wintalk /c servermachine 5150", "wintalk usage")
end sub 'showusage
end class 'app


' ui class for the sample
class talkform
inherits form

public sub new(talkerobj as talker)
' associate for method with the talker object
me.talkerobj = talkerobj
addhandler talkerobj.notifications, addressof handletalkernotifications

' create a ui elements
dim talksplitter as new splitter()
dim talkpanel as new panel()

receivetext = new textbox()
sendtext = new textbox()

'we'll support up to 64k data in our text box controls
receivetext.maxlength = 65536
sendtext.maxlength = 65536

statustext = new label()

' initialize ui elements
receivetext.dock = dockstyle.top
receivetext.multiline = true
receivetext.scrollbars = scrollbars.both
receivetext.size = new size(506, 192)
receivetext.tabindex = 1
receivetext.text = ""
receivetext.wordwrap = false
receivetext.readonly = true

talkpanel.anchor = anchorstyles.top or anchorstyles.bottom or anchorstyles.left or anchorstyles.right
talkpanel.controls.addrange(new control() {sendtext, talksplitter, receivetext})
talkpanel.size = new size(506, 371)
talkpanel.tabindex = 0

talksplitter.dock = dockstyle.top
talksplitter.location = new point(0, 192)
talksplitter.size = new size(506, 6)
talksplitter.tabindex = 2
talksplitter.tabstop = false

statustext.dock = dockstyle.bottom
statustext.location = new point(0, 377)
statustext.size = new size(507, 15)
statustext.tabindex = 1
statustext.text = "status:"

sendtext.dock = dockstyle.fill
sendtext.location = new point(0, 198)
sendtext.multiline = true
sendtext.scrollbars = scrollbars.both
sendtext.size = new size(506, 173)
sendtext.tabindex = 0
sendtext.text = ""
sendtext.wordwrap = false
addhandler sendtext.textchanged, addressof handletextchange
sendtext.enabled = false

autoscalebasesize = new size(5, 13)
clientsize = new size(507, 392)
controls.addrange(new control() {statustext, talkpanel})
me.text = "wintalk"

me.activecontrol = sendtext
end sub 'new


' when the app closes, dispose of the talker object
protected overrides sub onclosed(e as eventargs)
if not (talkerobj is nothing) then
removehandler talkerobj.notifications, addressof handletalkernotifications
talkerobj.dispose()
end if
mybase.onclosed(e)
end sub 'onclosed


' handle notifications from the talker object
private sub handletalkernotifications(notify as talker.notification, data as object)
select case notify
case talker.notification.initialized
' respond to status changes
case talker.notification.statuschange
dim statusobj as talker.status = ctype(data, talker.status)
statustext.text = string.format("status: {0}", statusobj)
if statusobj = talker.status.connected then
sendtext.enabled = true
end if
' respond to received text
case talker.notification.received
receivetext.text = data.tostring()
receivetext.selectionstart = int32.maxvalue
receivetext.scrolltocaret()
' respond to error notifications
case talker.notification.errornotify
close(data.tostring())
' respond to end
case talker.notification.endnotify
messagebox.show(data.tostring(), "closing wintalk")
close()
case else
close()
end select
end sub 'handletalkernotifications


' handle text change notifications and send talk
private sub handletextchange(sender as object, e as eventargs)
if not (talkerobj is nothing) then
talkerobj.sendtalk(ctype(sender, textbox).text)
end if
end sub 'handletextchange


' close with an explanation
private overloads sub close(message as string)
messagebox.show(message, "error!")
close()
end sub 'close

' private ui elements
private receivetext as textbox
private sendtext as textbox
private statustext as label
private talkerobj as talker

private sub talkform_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load

end sub

private sub initializecomponent()
'
'talkform
'
me.autoscalebasesize = new system.drawing.size(6, 14)
me.clientsize = new system.drawing.size(292, 273)
me.name = "talkform"

end sub
end class 'talkform


' an encapsulation of the sockets class used for socket chatting
class talker
implements idisposable

' construct a talker
public sub new(endpoint as ipendpoint, client as boolean)
me.endpoint = endpoint
me.client = client

socket = nothing
reader = nothing
writer = nothing

statustext = string.empty
prevsendtext = string.empty
prevreceivetext = string.empty
end sub 'new


' finalize a talker
overrides protected sub finalize()
dispose()
mybase.finalize()
end sub 'finalize


' dispose of resources and surpress finalization
public sub dispose() implements idisposable.dispose
gc.suppressfinalize(me)
if not (reader is nothing) then
reader.close()
reader = nothing
end if
if not (writer is nothing) then
writer.close()
writer = nothing
end if
if not (socket is nothing) then
socket.close()
socket = nothing
end if
end sub 'dispose


' nested delegate class and matchine event
delegate sub notificationcallback(notify as notification, data as object)
public event notifications as notificationcallback


' nested enum for notifications
public enum notification
initialized = 1
statuschange
received
endnotify
errornotify
end enum 'notification
' nested enum for supported states
public enum status
listening
connected
end enum 'status


' start up the talker's functionality
public sub start()
threadpool.queueuserworkitem(new system.threading.waitcallback(addressof establishsocket))
end sub 'start


' establish a socket connection and start receiving
private sub establishsocket(byval state as object)
try
' if not client, setup listner
if not client then
dim listener as socket

try
listener = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp)
listener.blocking = true
listener.bind(endpoint)
setstatus(status.listening)
listener.listen(0)
socket = listener.accept()
listener.close()
catch e as socketexception
' if there is already a listener on this port try client
if e.errorcode = 10048 then
client = true
endpoint = new ipendpoint(dns.resolve("127.0.0.1").addresslist(0), endpoint.port)
else
raiseevent notifications(notification.errornotify, "error initializing socket:" & controlchars.crlf & e.tostring())
end if
end try
end if

' try a client connection
if client then
dim temp as new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp)
temp.blocking = true
temp.connect(endpoint)
socket = temp
end if

' if it all worked out, create stream objects
if not (socket is nothing) then
setstatus(status.connected)
dim stream as new networkstream(socket)
reader = new streamreader(stream)
writer = new streamwriter(stream)
raiseevent notifications(notification.initialized, me)
else
raiseevent notifications(notification.errornotify, "failed to establish socket")
end if

' start receiving talk
' note: on w2k and later platforms, the networkstream.read()
' method called in receivetalke will generate an exception when
' the remote connection closes. we handle this case in our
' catch block below.
receivetalk()

' on win9x platforms, networkstream.read() returns 0 when
' the remote connection closes, prompting a graceful return
' from receivetalk() above. we will generate a notification.end
' message here to handle the case and shut down the remaining
' wintalk instance.
raiseevent notifications(notification.endnotify, "remote connection has closed.")

catch e as ioexception
dim sockexcept as socketexception = ctype(e.innerexception, socketexception)
if not (sockexcept is nothing) and 10054 = sockexcept.errorcode then
raiseevent notifications(notification.endnotify, "remote connection has closed.")
else
raiseevent notifications(notification.errornotify, "socket error:" & controlchars.crlf & e.message)
end if
catch e as exception
raiseevent notifications(notification.errornotify, "socket error:" & controlchars.crlf & e.message)
end try
end sub 'establishsocket


' send text to remote connection
public sub sendtalk(byval newtext as string)
dim send as string
' is this an append
if prevsendtext.length <= newtext.length and string.compareordinal(newtext, 0, prevsendtext, 0, prevsendtext.length) = 0 then
dim append as [string] = newtext.substring(prevsendtext.length)
send = string.format("a{0}:{1}", append.length, append)
' or a complete replacement
else
send = string.format("r{0}:{1}", newtext.length, newtext)
end if
' send the data and flush it out
writer.write(send)
writer.flush()
' save the text for future comparison
prevsendtext = newtext
end sub 'sendtalk


' send a status notification
private sub setstatus(byval statusobj as status)
me.statusobj = statusobj
raiseevent notifications(notification.statuschange, statusobj)
end sub 'setstatus


' receive chat from remote client
private sub receivetalk()
dim commandbuffer(19) as char
dim onebuffer(0) as char
dim readmode as integer = 1
dim counter as integer = 0
dim textobj as new stringbuilder()

while readmode <> 0
if reader.read(onebuffer, 0, 1) = 0 then
readmode = 0
goto continuewhile1
end if

select case readmode
case 1
if counter = commandbuffer.length then
readmode = 0
goto continuewhile1
end if
if onebuffer(0) <> ":"c then
commandbuffer(counter) = onebuffer(0)
counter = counter + 1
else
counter = convert.toint32(new string(commandbuffer, 1, counter - 1))
if counter > 0 then
readmode = 2
textobj.length = 0
else
if commandbuffer(0) = "r"c then
counter = 0
prevreceivetext = string.empty
raiseevent notifications(notification.received, prevreceivetext)
end if
end if
end if
case 2
textobj.append(onebuffer(0))
counter = counter - 1
if counter = 0 then
select case commandbuffer(0)
case "r"c
prevreceivetext = textobj.tostring()
case else
prevreceivetext += textobj.tostring()
end select
readmode = 1

raiseevent notifications(notification.received, prevreceivetext)
end if
case else
readmode = 0
goto continuewhile1
end select
continuewhile1:
end while
end sub 'receivetalk

private socket as socket

private reader as textreader
private writer as textwriter

private client as boolean
private endpoint as ipendpoint

private prevsendtext as string
private prevreceivetext as string
private statustext as string

private statusobj as status
end class 'talker

 
 收藏本文  打印本文  论坛讨论  关闭窗口
· 上一篇:对象与像素的选择
· 下一篇:自己写的自定义Web的上传控件
· 如何搞定DataGrid 分栏的大小
· 10天学会ASP.net之第五天
· 十天学会ASP.net(10)
· 关于VS.NET beta1安装问题
· 细细品味ASP.NET (五)


关于本站 | 联系我们 | 业务合作 | 客户案例 | 诚聘英才 | 广告合作 | 收藏本站
海口动网先锋网络科技有限公司版权所有
Copyright © 2000 - 2006 Cndw.Com
中华人民共和国电信与信息服务业务经营许可证编号 琼 ICP 020077