MSDN上的异步socket 服务端例子
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 服务端例子的更多相关文章
- GPS服务端(上)-Socket服务端(golang)
从第一次写GPS的服务端到现在,已经过去了八年时光.一直是用.net修修改改,从自己写的socket服务,到suppersocket,都是勉强在坚持着,没有真正的稳定过. 最近一段时间,服务端又出了两 ...
- Socket探索1-两种Socket服务端实现
介绍 一次简单的Socket探索之旅,分别对Socket服务端的两种方式进行了测试和解析. CommonSocket 代码实现 实现一个简单的Socket服务,基本功能就是接收消息然后加上结束消息时间 ...
- 在python中编写socket服务端模块(二):使用poll或epoll
在linux上编写socket服务端程序一般可以用select.poll.epoll三种方式,本文主要介绍使用poll和epoll编写socket服务端模块. 使用poll方式的服务器端程序代码: i ...
- AutoCAD.net支持后台线程-Socket服务端
最近因为公司项目的需求,CAD作为服务端在服务器中常驻运行,等待客户端远程发送执行任务的指令,最终确认用Socket-tcp通讯,CAD需要实时监听客户端发送的消息,这时就需要开启线程执行Socket ...
- Node.js:上传文件,服务端如何获取文件上传进度
内容概述 multer是常用的Express文件上传中间件.服务端如何获取文件上传的进度,是使用的过程中,很常见的一个问题.在SF上也有同学问了类似问题<nodejs multer有没有查看文件 ...
- C# Socket服务端与客户端通信(包含大文件的断点传输)
步骤: 一.服务端的建立 1.服务端的项目建立以及页面布局 2.各功能按键的事件代码 1)传输类型说明以及全局变量 2)Socket通信服务端具体步骤: (1)建立一个Socket (2)接收 ...
- socket服务端开发之测试使用threading和gevent框架
socket服务端开发之测试使用threading和gevent框架 话题是测试下多线程和gevent在socket服务端的小包表现能力,测试的方法不太严谨,也没有用event loop + pool ...
- 使用NewLife网络库构建可靠的自动售货机Socket服务端(一)
最近有个基于tcp socket 协议和设备交互需求,想到了新生命团队的各种组件,所以决定用NewLife网络库作为服务端来完成一系列的信息交互. 第一,首先说一下我们需要实现的功能需求吧 1,首先客 ...
- 第一个socket服务端程序
第一个socket服务端程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include ...
随机推荐
- 昼猫笔记 从此告别复杂代码--JavaScript
昼猫笔记--给你带来不一样的笔记 不止是笔记 更多的是思考 大家好,我是一只来自喵星的前端初学者,由于我们喵星人科技较为落后,昼猫从今天开始带着使命来到地球学习前端知识. 从今天开始,猫猫我就从Jav ...
- Hi3531D搭建环境时,出现的问题
1.展开SDK包得时候,运行./sdk.unpack得时候出现: 原因:ubuntu14.04中默认得是dash,要将dash改成bash. 解决方法:sudo ln -fs /bin/bash /b ...
- 【Linux端口大全】
2端口:管理实用程序 3端口:压缩进程 5端口:远程作业登录 7端口:回显 9端口:丢弃 11端口:在线用户 13端口:时间 17端口:每日引用 18端口:消息发送协议 19端口:字符发生器 20端口 ...
- 翻译《虚幻引擎4艺术大师 - 蓝图 III 》 中文版
本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/49800063 作者:c ...
- FragmentTransaction的commit和commitAllowingStateLoss的差别
1.什么是FragmentTransaction? 使用Fragment时.能够通过用户交互来运行一些动作.比方添加.移除.替换等. 全部这些改变构成一个集合,这个集合被叫做一个transaction ...
- zoj 2317 Nice Patterns Strike Back(矩阵乘法)
problemId=1317">http://acm.zju.edu.cn/onlinejudge/showProblem.do? problemId=1317 给出一个n*m的矩阵( ...
- JAVA基础实例(二)
1.做一个饲养员给动物喂食物的样例体现JAVA中的面向对象思想,接口(抽象类)的用处 package com.softeem.demo; /** *@authorleno *动物的接口 */ inte ...
- 面向对象(OO)基础
面向对象,英文Object-Oriented,简称OO),另外相关的还有:面向对象分析(Object-Oriented Analysis,OOA) 面向对象设计(Object-Oriented Des ...
- 79.QT解决迷宫问题(面向过程与面向对象)
面向过程: 创建一个类继承dialog,mydialog,添加两个变量 #ifndef MYDIALOG_H #define MYDIALOG_H #include <QDialog>&g ...
- 57.C++处理转义字符
#include <iostream> #include <string> #include <cstdlib> using namespace std; void ...