I have an Amcrest IP4M-1051 camera. The API for the camera enables two-way audio. Amcrest provides some freeware called, Amcrest Surveillance Pro, which demonstrates the functionality pretty well. I have a custom VB.NET WPF program in which I'm trying to replicate that functionality, using the NAudio library. My program can stream both the video and audio from the camera. I'm having trouble, though, streaming the audio picked up by my computer's microphone back to the camera. The code so far:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports NAudio.Wave
Class MainWindow
Dim tcpSender As New TcpClient
Dim endPoint As Net.IPEndPoint
Dim ipAddress As Net.IPAddress
Dim port As Integer
Private Sub Window_Loaded()
'ipAddress = System.Net.IPAddress.Parse("192.168.1.80")
'port = 554
'endPoint = New Net.IPEndPoint(ipAddress, port)
'tcpSender.Connect(endPoint)
Dim waveIn As New NAudio.Wave.WaveIn
waveIn.BufferMilliseconds = 50
waveIn.WaveFormat = New WaveFormat(44100, 2)
AddHandler waveIn.DataAvailable, AddressOf NAudio_DataAvailable
waveIn.StartRecording()
End Sub
Private Sub NAudio_DataAvailable(ByVal sender As Object, ByVal e As NAudio.Wave.WaveInEventArgs)
'Dim encoded() As Byte = codec.Encode(e.Buffer, 0, e.BytesRecorded)
'audioSender.Send(encoded)
Dim buffer As Byte() = e.Buffer 'Encoding.UTF8.GetBytes(e.Buffer)
Dim bytesRecorded As Integer = e.BytesRecorded
WriteToNetwork(buffer, bytesRecorded)
End Sub
Private Sub WriteToNetwork(ByVal buffer As Byte(), ByVal bytesRecorded As Integer)
'tcpSender.Client.Send(buffer)
Dim uri As New Uri("http://admin:PASSWORD#192.168.1.80/cgi-bin/audio.cgi?action=postAudio&httptype=singlepart&channel=1")
Dim request As HttpWebRequest
request = WebRequest.CreateHttp(uri)
request.Timeout = 4000
request.Method = "POST"
request.ContentType = "Audio/G.711A"
request.ContentLength = bytesRecorded
'
'Dim postStream = request.GetRequestStream
Using postStream As IO.Stream = request.GetRequestStream
postStream.Write(buffer, 0, bytesRecorded)
'Using response As HttpWebResponse = request.GetResponse
' Dim responseString As String = New IO.StreamReader(response.GetResponseStream()).ReadToEnd
' If Not String.IsNullOrEmpty(responseString) Then
' Console.WriteLine(responseString)
' End If
'End Using
End Using
End Sub
End Class
This code has a few issues. First of all, the camera is configured to receive AAC codec, and I have to use G.711A because I couldn't get AAC to work at all. By using the G.711A, the WriteToNetwork procedure works the first time (and the camera produces a second of static) and, on the second time, hangs at request.GetRequestStream, producing error: System.Net.WebException: 'The underlying connection was closed: The connection was closed unexpectedly.' Has anyone encountered this before?
Related
i'm using the above code to run a form with a tcplistener.
when the tcplistener recevie data from the client i need to write the data in in label1.text
i have tryed to use Shown instead of Load the form is showed but it the label text doesn't change.
How can i resolve this? any help will be appreciated.
thank you
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TcpServer()
End Sub
Shared Sub TcpServer()
Dim server As TcpListener
server = Nothing
Try
Dim port As Int32 = 4000
Dim localAddr As IPAddress = IPAddress.IPv6Any 'IPAddress.Parse("192.168.61.9") 'IPAddress.Any
server = New TcpListener(localAddr, port)
server.Start()
Dim bytes(1024) As Byte
Dim data As String = Nothing
While True
Console.WriteLine("Waiting for a connection... ")
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("Connected!")
data = Nothing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Form1.Label1.Text = data
' Process the data sent by the client.
'data = data.ToUpper()
data = "aaa"
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
' Send back a response.
stream.Write(msg, 0, msg.Length)
Console.WriteLine("Sent: {0}" + data)
i = stream.Read(bytes, 0, bytes.Length)
End While
' Shutdown and end connection
client.Close()
Form1.Refresh()
End While
Catch e As SocketException
MsgBox("SocketException: {0}", e.ToString)
Finally
server.Stop()
End Try
Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
Console.Read()
End Sub 'Main
Run TcpServer() on a new thread, or make use of BackGroundWorker Control which is part of winForms controls.
I am working on a project that have a server, whenever a clients connects it stores its user_id, ip in the dictionary which i have used. When I store the information between the different threads it is working but when I try to access the dictionary from different threads, it's not working well.
Let me clear what my code should do: There is one main thread active and listening for clients, when a clients wants to connect, main thread creates a child thread and that thread gets connected with client, client sends it a user_id, this user_id (as key for dictionary) and Tcpclient (as Value) get stored in dictionary. Further one client sends a message for particular client to server, that message contains the user_id for receiver. Now this client is connected with a particular thread which will check the key(user_id) in dictionary and then send the data to that client but dictionary is not giving the correct value for connected clients it just returns false even that client is connected.
Below is my code example.
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Public Class Mainform
Dim _server As TcpListener
Dim _listOfClients As New Dictionary(Of String, TcpClient)
Public MessageQueue As New Dictionary(Of String, Queue(Of String))
'Dim ClientData As StreamReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim port As Integer = 8888
_server = New TcpListener(System.Net.IPAddress.Any, port)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub NewClient()
Dim client As TcpClient = _server.AcceptTcpClient()
Dim toRec(100000) As Byte
Dim nss As NetworkStream = client.GetStream()
nss.Read(toRec, 0, toRec.Length)
Dim ClientData As String = Encoding.ASCII.GetString(toRec)
MsgBox("Client Connected: " & ClientData)
Dim too() As String
Dim status As Boolean = False
Dim sendto As String
Try
_listOfClients.Add(ClientData, client)
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
While True
Dim thisClient As String = ClientData
Dim ns As NetworkStream = client.GetStream()
Dim toRecieve(100000) As Byte
ns.Read(toRecieve, 0, toRecieve.Length)
Dim txt As String = Encoding.ASCII.GetString(toRecieve)
'MsgBox(txt)
too = txt.Split("#") 'server receives data in single string where user_id and message is connected with '#'
sendto = String.Copy(too(0)) 'this is the user_id of receiver client
If _listofclients.ContainsKey(sendto) Then
Dim data As String
data = String.Join("#", too)
Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
Dim nets As NetworkStream = _listofclients(sendto).GetStream()
nets.Write(buffer, 0, buffer.Length)
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.
sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.
Here is my code:
Public Class Form1
Private nSockets As ArrayList
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim IPHost As IPHostEntry
IPHost = Dns.GetHostByName(Dns.GetHostName())
lblStatus.Text = "My IP address is " +
IPHost.AddressList(0).ToString()
nSockets = New ArrayList()
Dim thdListener As New Thread(New ThreadStart _
(AddressOf listenerThread))
thdListener.Start()
End Sub
Public Sub listenerThread()
Control.CheckForIllegalCrossThreadCalls = False
Dim tcpListener As New TcpListener(7080)
Dim handlerSocket As Socket
Dim thdstHandler As ThreadStart
Dim thdHandler As Thread
tcpListener.Start()
Do
handlerSocket = tcpListener.AcceptSocket()
If handlerSocket.Connected Then
lbConnections.Items.Add(
handlerSocket.RemoteEndPoint.ToString() +
"connected.")
SyncLock (Me)
nSockets.Add(handlerSocket)
End SyncLock
thdstHandler = New ThreadStart(AddressOf _
handlerThread)
thdHandler = New Thread(thdstHandler)
thdHandler.Start()
End If
Loop
End Sub
Public Sub handlerThread()
Dim handlerSocket As Socket
handlerSocket = nSockets(nSockets.Count - 1)
Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
Dim blockSize As Int16 = 16
Dim thisRead As Int16
Dim dataByte(blockSize) As Byte
SyncLock Me
' Only one process can access the
' same file at any given time
Dim fileStream As Stream
fileStream = File.OpenWrite("C:\Whatever.file")
While (True)
thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
fileStream.Write(dataByte, 0, thisRead)
If thisRead = 0 Then Exit While
End While
fileStream.Close()
networkStream.Close()
End SyncLock
lbConnections.Items.Add("File Written")
handlerSocket = Nothing
End Sub
How do i make it IPv6 capable?
Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.
Private Sub Sendfile()
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(tbFilename.Text)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(tbServer.Text, 7080)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)
networkStream.Close()
End Sub
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.
You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.
Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)
As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.
I'm trying to build a windows service tcpip server to install on some computer to be able to send messages to them...
The following code is working perfectly if I run it as a normal windows application but if I use it to create a windows service it doesn't run as expected.
Throught the Visual studio "attach debug" I can see the debug and every time I send a request from the client I see this:
The thread 0xf34 has exited with code 259 (0x103).
That means the thread was entered but no output, or console.write...
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Main
Private serverSocket As TcpListener
Private Delegate Sub WriteMessageDelegate(ByVal msg As String)
Dim listenThread As New Thread(New ThreadStart(AddressOf ListenForClients))
Private Sub ListenForClients()
serverSocket = New TcpListener(IPAddress.Any, 11000)
serverSocket.Start()
Console.WriteLine("Listen for clients...")
While True 'blocks until a client has connected to the server
Dim client As TcpClient = Me.serverSocket.AcceptTcpClient()
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf HandleClientComm))
clientThread.Start(client)
End While
End Sub
Private Sub HandleClientComm(ByVal client As Object)
Dim tcpClient As TcpClient = DirectCast(client, TcpClient)
Dim clientStream As NetworkStream = tcpClient.GetStream()
Dim message As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
Console.WriteLine("Handle client comm...")
While True
bytesRead = 0
bytesRead = clientStream.Read(message, 0, 4096) 'blocks until a client sends a message
If bytesRead = 0 Then
Exit While 'the client has disconnected from the server
End If
'message has successfully been received
'Dim encoder As New ASCIIEncoding()
'Dim serverResponse As String = "Response to send"
'Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
'clientStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(bytesRead)
'message has successfully been received
Dim encoder As New ASCIIEncoding()
' Convert the Bytes received to a string and display it on the Server Screen
Dim msg As String = encoder.GetString(message, 0, bytesRead)
Console.WriteLine(msg)
'WriteMessage(msg)
End While
tcpClient.Close()
End Sub
Private Function BytesToString(
ByVal bytes() As Byte) As String
Return Encoding.Default.GetString(bytes)
End Function
Private Sub WriteMessage(ByVal msg As String)
If Me.MessagesLog.InvokeRequired Then
Dim d As New WriteMessageDelegate(AddressOf WriteMessage)
Me.MessagesLog.Invoke(d, New Object() {msg})
Else
Me.MessagesLog.AppendText(msg & Environment.NewLine)
End If
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
listenThread.Start()
Console.WriteLine("Starting...")
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
'listenThread.Abort()
End Sub
End Class
Can someone help me?
Found the problem...
Windows services dont do output to console.write()... it has to be with debug.print()
"The Thread..." output is normal..
Thank you,
AP
I'm making a website scraper for a project I'm doing. I've gotten everything to work great, however, loading the actual page takes F-O-R-E-V-E-R. You can see the page it's loading here:
MCServerList.Net
Here is the code I am using:
private CONST REQUESTURL as string = "http://www.MCServerList.net/?page="
private chunkId as int32 = 1
Dim req As HttpWebRequest = WebRequest.Create(REQUESTURL & chunkId)
Dim res As HttpWebResponse = req.GetResponse()
Dim Stream As Stream = res.GetResponseStream()
I then use "Stream" and load it through the HTMLAgilityPack found free online. It loads the page quickly, however, the initial request usually takes ~20-30 seconds.
Any help would be appreciated!
I just ran the following code and ignoring the first initial compile I average about 3.3 seconds for GetResponse() and 0.2 more seconds for Load(). Are you on a fast connection? Are you sure this is where the bottleneck is?
Option Explicit On
Option Strict On
Imports System.Net
Public Class Form1
Private Const REQUESTURL As String = "http://www.MCServerList.net/?page="
Private chunkId As Int32 = 1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ST As New System.Diagnostics.Stopwatch()
ST.Start()
Dim req = WebRequest.Create(REQUESTURL & chunkId)
Dim res = req.GetResponse()
Trace.WriteLine(String.Format("GetResponse() : {0}", ST.Elapsed))
Using Stream As System.IO.Stream = res.GetResponseStream()
Dim X As New HtmlAgilityPack.HtmlDocument()
X.Load(Stream)
End Using
Trace.WriteLine(String.Format("Load() : {0}", ST.Elapsed))
ST.Stop()
End Sub
End Class