我有使用TCP连接从客户端向服务器发送字符串的代码。 但我不知道如何将其转换为NonBlocking TCP状态连接。 我试着把socket.Blocking = FALSE,但那段代码给我一个错误。
套接字错误代码:10035
异常标题:无法立即完成非阻塞套接字操作
这是我从客户端向服务器发送字符串的代码。
服务器代码:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim soket As Socket
Sub Main()
Try
Dim alamatIP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim tcpListener As New TcpListener(alamatIP, 8000)
'soket.Blocking = False - THIS WILL GIVE ME AN ERROR
tcpListener.Start()
System.Console.WriteLine("Server port 8000...")
Dim myendpoint As IPEndPoint
myendpoint = CType(tcpListener.LocalEndpoint, IPEndPoint)
System.Console.WriteLine("IP : " + myendpoint.Address.ToString + " and port is " + myendpoint.Port.ToString)
System.Console.WriteLine("Waiting for connection !")
soket = tcpListener.AcceptSocket()
myendpoint = CType(soket.RemoteEndPoint(), IPEndPoint)
System.Console.WriteLine("Receiving from " + myendpoint.Address.ToString())
Dim bitData(100) As Byte
Dim newString As String = ""
Do
Try
Dim size As Integer = soket.Receive(bitData)
newString = Encoding.ASCII.GetString(bitData)
Console.WriteLine(newString)
Array.Clear(bitData, 0, bitData.Length)
Catch ex As Exception
Console.Write(ex.ToString())
End Try
Loop While newString <> "exit"
soket.Close()
tcpListener.Stop()
Catch ex As Exception
Console.WriteLine("Error ..." + ex.ToString())
End Try
Console.ReadLine()
End Sub
End Module
客户代码:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Module Module1
Sub Main()
Try
Dim tcpClient As New TcpClient 'creating the client
Console.WriteLine("Connecting....")
tcpClient.Connect("127.0.0.1", 8000) 'connecting the client the server
'port is same as in the server
Console.WriteLine("Connected")
Console.WriteLine("Enter the string to be transmitted : ")
Dim strMessage As String
Dim stm As Stream
Dim counter As Integer = 0
Do
stm = tcpClient.GetStream() 'getting the stream of the client
Dim ascenc As New ASCIIEncoding
strMessage = Console.ReadLine()
Dim byteData() As Byte = ascenc.GetBytes(strMessage)
Console.WriteLine("Transmitted ")
stm.Write(byteData, 0, byteData.Length())
Loop While strMessage <> "exit"
tcpClient.Close() 'closing the connection
Catch ex As Exception
Console.WriteLine("Error..." + ex.StackTrace.ToString()) 'writing the exception into the console
End Try
End Sub
End Module
感谢您的帮助。
答案 0 :(得分:1)
当您尝试从非阻塞套接字读取或写入它并且此操作无法立即完成时,则套接字应该发出错误信号。在VB中,它意味着它应该引发异常。例如,当您的计算机未收到任何数据但您尝试Read
某些内容时,会发生这种情况。
在非阻塞套接字上尝试操作之前,请调用Select
或Poll
以确保它已准备好进行操作。