MSDN上的异步socket 服务端例子

2006-11-22 17:12:01|  分类: 代码学习 |  标签: |字号大中小 订阅

 
 

Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

' Receive buffer.
    Public buffer(BufferSize) As Byte
    ' Received data string.
    Public sb As New StringBuilder()
End Class 'StateObject

Public Class AsynchronousSocketListener

' Incoming data from the client.
    Public Shared data As String = Nothing

' Thread signal.
    Public Shared allDone As New ManualResetEvent(False)

Public Sub New()

End Sub 'New

Public Shared Sub StartListening()
        ' Data buffer for incoming data.
        Dim bytes() As Byte = New [Byte](1024) {}

' Establish the local endpoint for the socket.
        ' The DNS name of the computer
        ' running the listener is "host.contoso.com".
        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
        Dim localEndPoint As New IPEndPoint(ipAddress, 11000)

' Intializes a TCP/IP socket.
        Dim listener As New Socket(AddressFamily.InterNetwork, _
            SocketType.Stream, ProtocolType.Tcp)

)

While True
                ' Set the event to nonsignaled state.
                allDone.Reset()

' Start an asynchronous socket to listen for connections.
                Console.WriteLine ( "Waiting for a connection..." )
                listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), _
                listener)

' Wait until a connection is made before continuing.
                allDone.WaitOne()
            End While

Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try

Console.WriteLine(ControlChars.Cr + "Press ENTER to continue...")
        Console.Read()
    End Sub 'StartListening

Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
        ' Signal the main thread to continue.
        allDone.Set()

' Get the socket that handles the client request.
        Dim listener As Socket = CType(ar.AsyncState, Socket)
        Dim handler As Socket = listener.EndAccept(ar)

, StateObject.BufferSize, , _
            New AsyncCallback(AddressOf ReadCallback), state)
    End Sub 'AcceptCallback

Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
        Dim content As [String] = [String].Empty

' Retrieve the state object and the handler socket
        ' from the asynchronous state object.
        Dim state As StateObject = CType(ar.AsyncState, StateObject)
        Dim handler As Socket = state.workSocket

' Read data from client socket.
        Dim bytesRead As Integer = handler.EndReceive(ar)

Then
            ' There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, _
                bytesRead))

' Check for end-of-file tag. If it is not there, read
            ' more data.
            content = state.sb.ToString()
            If content.IndexOf("<EOF>") > -1 Then
                ' All the data has been read from the
                ' client. Display it on the console.
                Console.WriteLine( "Read {0} bytes from socket. " + _
                    ControlChars.Cr + " Data : {1}", content.Length, content)
                ' Echo the data back to the client.
                Send(handler, content)
            Else
                ' Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, _
                    0, New AsyncCallback(AddressOf ReadCallback), state)
            End If
        End If
    End Sub 'ReadCallback

Private Shared Sub Send(ByVal handler As Socket, ByVal data As [String])
        ' Convert the string data to byte data using ASCII encoding.
        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)

' Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0, _
            New AsyncCallback(AddressOf SendCallback), handler)
    End Sub 'Send

Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
        Try
            ' Retrieve the socket from the state object.
            Dim handler As Socket = CType(ar.AsyncState, Socket)

' Complete sending the data to the remote device.
            Dim bytesSent As Integer = handler.EndSend(ar)
            Console.WriteLine("Sent {0} bytes to client.", bytesSent)

handler.Shutdown(SocketShutdown.Both)
            handler.Close()

Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try
    End Sub 'SendCallback

'Entry point that delegates to C-style main Private Function.
    Public Overloads Shared Sub Main()
        System.Environment.ExitCode = _
        Main(System.Environment.GetCommandLineArgs())
    End Sub

Public Overloads Shared Function Main(ByVal args() As [String]) As Integer
        StartListening()
        Return 0
    End Function 'Main
End Class 'AsynchronousSocketListener

MSDN上的异步socket 服务端例子的更多相关文章

  1. GPS服务端(上)-Socket服务端(golang)

    从第一次写GPS的服务端到现在,已经过去了八年时光.一直是用.net修修改改,从自己写的socket服务,到suppersocket,都是勉强在坚持着,没有真正的稳定过. 最近一段时间,服务端又出了两 ...

  2. Socket探索1-两种Socket服务端实现

    介绍 一次简单的Socket探索之旅,分别对Socket服务端的两种方式进行了测试和解析. CommonSocket 代码实现 实现一个简单的Socket服务,基本功能就是接收消息然后加上结束消息时间 ...

  3. 在python中编写socket服务端模块(二):使用poll或epoll

    在linux上编写socket服务端程序一般可以用select.poll.epoll三种方式,本文主要介绍使用poll和epoll编写socket服务端模块. 使用poll方式的服务器端程序代码: i ...

  4. AutoCAD.net支持后台线程-Socket服务端

    最近因为公司项目的需求,CAD作为服务端在服务器中常驻运行,等待客户端远程发送执行任务的指令,最终确认用Socket-tcp通讯,CAD需要实时监听客户端发送的消息,这时就需要开启线程执行Socket ...

  5. Node.js:上传文件,服务端如何获取文件上传进度

    内容概述 multer是常用的Express文件上传中间件.服务端如何获取文件上传的进度,是使用的过程中,很常见的一个问题.在SF上也有同学问了类似问题<nodejs multer有没有查看文件 ...

  6. C# Socket服务端与客户端通信(包含大文件的断点传输)

    步骤: 一.服务端的建立 1.服务端的项目建立以及页面布局 2.各功能按键的事件代码 1)传输类型说明以及全局变量 2)Socket通信服务端具体步骤:   (1)建立一个Socket   (2)接收 ...

  7. socket服务端开发之测试使用threading和gevent框架

    socket服务端开发之测试使用threading和gevent框架 话题是测试下多线程和gevent在socket服务端的小包表现能力,测试的方法不太严谨,也没有用event loop + pool ...

  8. 使用NewLife网络库构建可靠的自动售货机Socket服务端(一)

    最近有个基于tcp socket 协议和设备交互需求,想到了新生命团队的各种组件,所以决定用NewLife网络库作为服务端来完成一系列的信息交互. 第一,首先说一下我们需要实现的功能需求吧 1,首先客 ...

  9. 第一个socket服务端程序

    第一个socket服务端程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include ...

随机推荐

  1. OpenSUSE下支持托盘的邮件客户端Sylpheed

    在网上搜索了很多客户端想支持系统托盘,发现一个很不错的邮件客户端Sylpheed.设置方式和foxmail很像,最为重要的是支持系统托盘,很方便,默认没有开启,简单设置下:配置->通用首选项-& ...

  2. Oracle Database Sample Schemas

    本文在Creative Commons许可证下发布 最近在钻研Oracle 11gR2,写SQL缺乏Demo表,研究他家的官方资料时发现一块甲骨文已经给我们准备Sample Schemas.比如说SC ...

  3. tsp问题——遗传算法解决

    TSP问题最简单的求解方法是枚举法. 它的解是多维的.多局部极值的.趋于无穷大的复杂解的空间.搜索空间是n个点的全部排列的集合.大小为(n-1)! .能够形象地把解空间看成是一个无穷大的丘陵地带,各山 ...

  4. Maven实战(八)---模块划分

    为了防止传递依赖,我们各个模块之间尽量用直接依赖的方式.本篇文章介绍多模块化开发.我们做过Maven项目的都知道.我们的项目一般都是分模块的,每一个模块都会相应着一个POM.xml文件,它们之间通过继 ...

  5. android 图片特效处理之 图片叠加

    这篇将讲到图片特效处理的图片叠加效果.跟前面一样是对像素点进行处理,可参照前面的android图像处理系列之七--图片涂鸦,水印-图片叠加和android图像处理系列之六--给图片添加边框(下)-图片 ...

  6. jquery中最常用的API有哪些

    jquery中最常用的API有哪些 一.总结 一句话总结:取html的方法,class相关的方法,val相关的方法,data相关的方法,attr相关的方法 1.jQuery Object Access ...

  7. Onvif开发之客户端搜索篇

    关于ONVIF的广播,有客户端搜索和服务端发现的区别:客户端向固定的网段和固定的端口发送广播消息,服务端在对应的端口回复广播请求消息本文首先介绍客户端如何进行广播的已经对广播回复的信息的基本处理. 客 ...

  8. js---对象 和 函数this

    一:对象创建的方法 //普通 字面量形式 var obj = { name:'名字', fn:function(){ console.log(this.name); } } //new 实例 var ...

  9. Web跨域问题基础

    同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响.可以说Web是构建在同源策略基础之上的,浏览器只 ...

  10. Mvc异步

    <h3>MVC 自带的yibu请求</h3> <%-- 1.要执行的方法,2.控制器,3.Ajax操作--%> <%using (Ajax.BeginForm ...