0
我有代碼發送字符串從客戶端到服務器與TCP連接。 但我不知道如何將其轉換爲NonBlocking TCP狀態連接。 我試圖把socket.Blocking = FALSE,但該代碼給我一個錯誤。VB.net TCP非阻塞狀態
插槽錯誤代碼: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
感謝您的幫助。
你累了服務器機器的本地IP地址嗎? –
你爲什麼要讓它不阻塞?這會破壞你的代碼非常糟糕,因爲它旨在等待信息。你有沒有聽說過_asynchronous sockets_? ([** client **](https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example)和[** server **](https: //docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example)示例)請注意,您仍然必須在「Main」方法中放置一個「等待」,以便它直到你說它可以這樣做,纔會退出應用程序。 –
難以使它成爲非阻塞套接字嗎?有任何引用使非阻塞tcp服務器。 –