保持持久连接(AsynchronousSocketListener) [英] Maintain a Persistent Connection (AsynchronousSocketListener)
问题描述
以下代码说明:此服务器等待连接,然后使用异步操作接受连接,从连接的客户端获取数据,将数据回送给连接的客户端。然后它断开与客户端的连接并等待另一个客户端。
问题:如何让它不与客户端断开连接并保持与客户端的持久连接?<br>
Imports System |
Imports System.Net |
Imports System.Net.Sockets |
Imports System.Text |
Imports System.Threading |
Imports Microsoft.VisualBasic |
'用于异步读取客户端数据的状态对象 |
Public 类 StateObject |
< font style ="font-size:11px; color:green">'客户端套接字。 |
Public < font style ="font-size:11px"> workSocket As Socket = Nothing |
'接收缓冲区的大小。 |
Public < font style ="font-size:11px"> Const BufferSize As Integer = 1024 | "接收缓冲区。 |
Public < font style ="font-size:11px"> buffer(BufferSize) As 字节 |
'收到的数据字符串。 |
Public < font style ="font-size:11px"> sb As 新 StringBuilder |
End 类 'StateObject |
公共 Class AsynchronousSocketListener |
'线程信号。 |
Public < font style ="font-size:11px"> Shared allDone As New ManualResetEvent( False ) |
'此服务器等待连接然后使用异步操作 |
'接受连接,从连接的客户端获取数据, |
"回响数据返回给所述连接的客户端。 |
"然后,它从客户端断开,并等待另一个客户端。 |
公共 共享 Sub Main() |
"传入数据Data缓冲器。 |
Dim bytes() As < font style ="font-size:11px"> Byte = 新 [ 字节 ](1023){} |
Dim < font style ="font-size:11px"> ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName()) |
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0) |
Dim LO calEndPoint As 新 IPEndPoint(ipAddress,11000) |
"创建TCP / IP套接字。 |
Dim listener As 新 套接字(AddressFamily。 InterNetwork,SocketType.Stream,ProtocolType.Tcp) |
'将套接字绑定到本地端点并侦听传入连接。 |
listener.Bind(localEndPoint) |
listener.Listen(100) |
而 True |
'将事件设置为无信号状态。 |
allDone.Reset() |
'启动异步套接字侦听连接。 |
Console.WriteLine( "等待连接......" ) |
listener.BeginAccept( New AsyncCallback( AddressOf AcceptCallback),监听器) |
"等待直到建立连接并且继续之前处理。 |
allDone.WaitOne() |
结束 而 |
结束 Sub '主要 |
公共 共享 Sub AcceptCallback ( ByVal ar As IAsyncResult) |
"获取,处理客户端请求的插座。 |
Dim listener As Socket = CType (ar .AsyncState,Socket) |
'结束操作。 |
Dim handler As Socket = listener.EndAccept(ar) |
< font style ="font-size:11px"> '为状态对象创建异步接收。 |
Dim < font style ="font-size:11px"> state As 新 StateObject |
state.workSocket = handler |
handler。 BeginReceive(state.buffer,0,StateObject.BufferSize,0, New AsyncCallback( AddressOf ReadCallback),s tate) |
End Sub 'AcceptCallback |
Dim content As String = 字符串 。清空 |
'检索状态对象和处理程序套接字 |
"从异步状态对象。 |
Dim state As StateObject = CType (ar .AsyncState,StateObject) |
Dim handler As Socket = state.workSocket |
'读取数据从客户端套接字。 |
Dim bytesRead As 整数 = handler.EndReceive (ar) |
如果 bytesRead> 0 然后 |
'可能有更多数据,因此存储到目前为止收到的数据。 |
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)) |
"检查结束文件标签。如果不存在,请阅读 |
"更多的数据。 |
content = state.sb.ToString() |
如果 content.IndexOf( "< EOF>" )> -1 然后 |
'所有数据都是从 |
'client。显示在控制台上。 |
Console.WriteLine( "从套接字读取{0}个字节。" + vbLf + "数据:{1}" ,content.Length,content) |
'将数据回显给客户端。 |
发送(处理程序,内容) |
Else |
"不接收的所有数据。获取更多。 |
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0, New AsyncCallback( AddressOf ReadCallback),州) |
结束 If |
结束 如果 |
End Sub 'ReadCallback |
私人 共享 Sub |
< font style ="font-size:11px"> '使用ASCII编码将字符串数据转换为字节数据。 |
Dim byteData As 字节 ()=编码.ASCII.GetBytes(数据) |
' 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) |
’ 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(Sock etShutdown.Both) |
handler.Close() |
’ Signal the main thread to continue. |
allDone.Set() |
End Sub ’SendCallback |
End Class ’AsynchronousSocketListener |
The following code states: This server waits for a connection and then uses asynchronous operations to accept the connection, get data from the connected client, echo that data back to the connected client. It then disconnects from the client and waits for another client.
QUESTION: How do I get it to not disconnect from the client and maintain it's persistent connection to the client?
Imports System |
Imports System.Net |
Imports System.Net.Sockets |
Imports System.Text |
Imports System.Threading |
Imports Microsoft.VisualBasic |
' State object for reading client data asynchronously |
Public Class StateObject |
' Client socket. |
Public workSocket As Socket = Nothing |
' Size of receive buffer. |
Public Const BufferSize As Integer = 1024 |
' Receive buffer. |
Public buffer(BufferSize) As Byte |
' Received data string. |
Public sb As New StringBuilder |
End Class 'StateObject |
Public Class AsynchronousSocketListener |
' Thread signal. |
Public Shared allDone As New ManualResetEvent(False) |
' This server waits for a connection and then uses asychronous operations to |
' accept the connection, get data from the connected client, |
' echo that data back to the connected client. |
' It then disconnects from the client and waits for another client. |
Public Shared Sub Main() |
' Data buffer for incoming data. |
Dim bytes() As Byte = New [Byte](1023) {} |
' Establish the local endpoint for the socket. |
Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName()) |
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0) |
Dim localEndPoint As New IPEndPoint(ipAddress, 11000) |
' Create a TCP/IP socket. |
Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) |
' Bind the socket to the local endpoint and listen for incoming connections. |
listener.Bind(localEndPoint) |
listener.Listen(100) |
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 and processed before continuing. |
allDone.WaitOne() |
End While |
End Sub 'Main |
Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult) |
' Get the socket that handles the client request. |
Dim listener As Socket = CType(ar.AsyncState, Socket) |
' End the operation. |
Dim handler As Socket = listener.EndAccept(ar) |
' Create the state object for the async receive. |
Dim state As New StateObject |
state.workSocket = handler |
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 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 the client socket. |
Dim bytesRead As Integer = handler.EndReceive(ar) |
If bytesRead > 0 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. " + vbLf + " 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) |
' 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() |
' Signal the main thread to continue. |
allDone.Set() |
End Sub 'SendCallback |
End Class 'AsynchronousSocketListener |
推荐答案
One way to do this is to read through all the code, line by line, and look up every function on MSDN. Once you understand how the code works, changing it to maintain a persistent connection will be natural.
One way to do this is to read through all the code, line by line, and look up every function on MSDN. Once you understand how the code works, changing it to maintain a persistent connection will be natural.
-Steve
-Steve
这篇关于保持持久连接(AsynchronousSocketListener)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!