I am coding a poker game in vb.net, and I want to create a multiplayer game using the internet, whether it being on WAN or LAN. I really have no idea where to start, and I don't know what to search on Google. I know that I will have to listen on a port, and I need to send and receive packets. No searches on Google are helping. Any links/ideas?
Also, how would I be able to show a list box of all the games currently in progress and allow the user to join? And how to create a new game?
I'd recommend learning the UdpClient class, it's a good option for beginners.
You first start by 'setting up' two clients, one to send data, and one to listen for incoming data. Once you've assigned the clients with the appropriate addresses and port numbers you then start the listening client in a loop, so that you can consistently listen for data.
Then you 'wire up' your sending client to some form of trigger, (in the example i've given below, i've set my sending client up to a button event) so you can send data at irregular intervals, or you can set your client in a loop to continuously send data.
Once you've done that, you now need to convert the data you want to send from string to a byte array, then you can finally send it, and vis versa for receiving data (from byte array to string).
Here's a simple example,
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Public Class Form1
Private Const port As Integer = 9653 'Or whatever port number you want to use
Private Const broadcastAddress As String = "255.255.255.255"
Private receivingClient As UdpClient
Private sendingClient As UdpClient
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
InitializeSender()
InitializeReceiver()
End Sub
Private Sub InitializeSender()
sendingClient = New UdpClient(broadcastAddress, port) 'Use broadcastAddress for sending data locally (on LAN), otherwise you'll need the public (or global) IP address of the machine that you want to send your data to
sendingClient.EnableBroadcast = True
End Sub
Private Sub InitializeReceiver()
receivingClient = New UdpClient(port)
ThreadPool.QueueUserWorkItem(AddressOf Receiver) 'Start listener on another thread
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim stringToSend As String = TextBox1.Text 'Assuming you have a textbox with the data you want to send
If (Not String.IsNullOrEmpty(stringToSend)) Then
Dim data() As Byte = Encoding.ASCII.GetBytes(stringToSend)
sendingClient.Send(data, data.Length)
End If
End Sub
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP on the specified port
Do While True 'Notice that i've setup an infinite loop to continually listen for incoming data
Dim data() As Byte
data = receivingClient.Receive(endPoint)
Dim message As String = Encoding.ASCII.GetString(data) 'Recived data as string
Loop
End Sub
End Class
And now for adding a list box for available games.
Short answer, it's impossible very, very hard to do unless you have a server.
Longer answer, you'll need a server, and assuming you have a server you'll need to create an additional program to handle the data that's being sent to it, and to send data to other users.
I could go on to explain how to setup the additional program etc, etc, but judging that your network programming skills are still 'spreading out their wings', I'd suggest that you leave out advanced features like this until you have some more experience, then when you're more confident have a try by yourself and if you're still struggling just pop a question on here and I'm sure someone will help you.
Related
I want to read a custom event log which is stored under Applications and services log section in Windows Eventlog.
Unfortunately when calling the Log according to its naming properties I receive an error message that the log cannot be found.
Ulitmately I try read event details from events with a specific ID but first I need to able to access the log.
This is the code that I have so far:
Imports System
Imports System.Diagnostics.Eventing.Reader
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As New EventLog("Logname as per Properties", System.Environment.MachineName)
Dim elEventEntry As System.Diagnostics.EventLogEntry
Dim nmbr As Integer = query.Entries.Count
MsgBox(nmbr)
End Sub
End Class
This is the structure in the eventlog (I want to read the blue highlighted part)
Anybody any idea how to determine the correct log name?
Thx & BR
Daniel
For many of the event logs, you need to use an EventLogQuery.
As an example, if you wanted to query the "Setup" event log to count the number of entries with an EventID of 1, you could do this:
Imports System.Diagnostics.Eventing.Reader
Module Module1
Sub Main()
Dim query As New EventLogQuery("Setup", PathType.LogName, "*[System/EventID=1]")
Dim nEvents = 0
Using logReader = New EventLogReader(query)
Dim eventInstance As EventRecord = logReader.ReadEvent()
While Not eventInstance Is Nothing
nEvents += 1
eventInstance = logReader.ReadEvent()
End While
End Using
Console.WriteLine(nEvents)
Console.ReadLine()
End Sub
End Module
You can see the names of the items to query by looking at the XML for an event in Windows Event Viewer.
The Using construct makes sure that the EventLogReader is properly disposed of after it's been used.
Further information: How to: Access and Read Event Information (from Microsoft).
I am trying to communicate with application written in Visual basic. When i send data from application to board everything works perfectly, but in other direction it doesn't work. I do follow network traffic with wireshark and everything seems ok. When send data from board with PIC to application(PC) I can see it in wireshark, but I can't detect any data inside of application I think that my problem is at application , I am not very good at VB programming, not good at all..this is my first program.. I've attached code so you can see what I've done. Application(PC) ip address 192.168.1.11, pic ip address 192.168.1.10 (mask 255.255.255.0). So if someone could give me advice I would be very grateful..
PS. sorry for my bad english.
Imports System.Net
Imports System.Net.Sockets
Imports System.Text.Encoding
Imports System.Text
Public Class Form1
Dim controlData() As Byte = {&H55, &H55, &H55, &H55, &H55}
Const portTo As Integer = 5000
Const portFrom As Integer = 5001
Dim udpTransmit As New Sockets.UdpClient(portFrom)
Dim udpReceive As New Sockets.UdpClient(portTo)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnTo.Click
udpTransmit.Connect(tbToIp.Text, portTo)
udpTransmit.Send(controlData, controlData.Length)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Try
Dim ep As New IPEndPoint(tbToIp.Text, portTo)
Do
Dim receiveData() As Byte = udpReceive.Receive(ep)
text1.Text = ASCII.GetString(receiveData)
Loop
Catch ex As Exception
End Try
End Sub
End Class
[data form PIC to PC]
[data from PC to PIC]1
I am trying to read serial data that Arduino is sending but it keeps giving me over and over the first string that it receives even if I change the Arduino output. Why does it give me only first value and not update?
Module Module1
Sub Main()
Dim com4 As IO.Ports.SerialPort = Nothing
com4 = My.Computer.Ports.OpenSerialPort("COM4")
Dim incoming As String
Do
incoming = com4.ReadLine()
Console.WriteLine(incoming)
Threading.Thread.Sleep(250)
Loop
End Sub
End Module
It could be, that depending on your arduino sketch, it sends the same data out for some time, filling up the receive buffer, which is what gets read for some time in your Do loop.
Try using events
dim withevents com4 as serialport.......
sub datareceivedhandler (sender as object, e as eventargs) handles com4.datareceived
dim incoming as string = com4.readline
console.writeline(incoming)
end sub
So I'm trying to make a very simple system to send messages from a client to a server (and later on from server to client as well, but baby steps first). I'm not sure exactly how to use UDPClient to send and receive messages (especially to receive them), mostly because I don't have anything triggering the ReceiveMessage() function and I'm not sure what would.
Source Code is at this link, go to File>Download. It is already built if you want to just run the exe.
So my question is basically: How can I easily use UDPClient, how can I get this system to work and what are some tips for executing this kind of connection? Anything I should watch out for (threading, issues with code,etc)?
Source.
You need first need to set up two UdpClients. One client for listening and the other for sending data. (You'll also need to pick a free/unused port number and know the IP address of your target - the machine you want to send data to.)
To set up the receiver,
Instantiate your UdpClient variable with the port number you chose earlier,
Create a new thread to avoid blocking while receiving data,
Loop over the client's receive method for as long as you want to receive data (the loop's execution should be within the new thread),
When you receive one lot of data (called a "packet") you may need to convert the byte array to something more meaningful,
Create a way to exit the loop when you want to finish receiving data.
To set up the sender,
Instantiate your UdpClient variable with the port number you chose earlier (you may want to enable the ability to send broadcast packets. This allows you to send data to all listeners on your LAN),
When you need to transmit data, convert the data to a byte array and then call Send().
I'd suggest that you have a quick skim read through this.
Here's some code to get you started off...
'''''''''''''''''''''''Set up variables''''''''''''''''''''
Private Const port As Integer = 9653 'Port number to send/recieve data on
Private Const broadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
Private receivingClient As UdpClient 'Client for handling incoming data
Private sendingClient As UdpClient 'Client for sending data
Private receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Private closing As Boolean = False 'Used to close clients if form is closing
''''''''''''''''''''Initialize listening & sending subs'''''''''''''''''
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
InitializeSender() 'Initializes startup of sender client
InitializeReceiver() 'Starts listening for incoming data
End Sub
''''''''''''''''''''Setup sender client'''''''''''''''''
Private Sub InitializeSender()
sendingClient = New UdpClient(broadcastAddress, port)
sendingClient.EnableBroadcast = True
End Sub
'''''''''''''''''''''Setup receiving client'''''''''''''
Private Sub InitializeReceiver()
receivingClient = New UdpClient(port)
Dim start As ThreadStart = New ThreadStart(AddressOf Receiver)
receivingThread = New Thread(start)
receivingThread.IsBackground = True
receivingThread.Start()
End Sub
'''''''''''''''''''Send data if send button is clicked'''''''''''''''''''
Private Sub sendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendBut.Click
Dim toSend As String = tbSend.Text 'tbSend is a textbox, replace it with whatever you want to send as a string
Dim data() As Byte = Encoding.ASCII.GetBytes(toSend)'Convert string to bytes
sendingClient.Send(data, data.Length) 'Send bytes
End Sub
'''''''''''''''''''''Start receiving loop'''''''''''''''''''''''
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port (I personally select 9653)
While (True) 'Setup an infinite loop
Dim data() As Byte 'Buffer for storing incoming bytes
data = receivingClient.Receive(endPoint) 'Receive incoming bytes
Dim message As String = Encoding.ASCII.GetString(data) 'Convert bytes back to string
If closing = True Then 'Exit sub if form is closing
Exit Sub
End If
End While
End Sub
'''''''''''''''''''Close clients if form closes''''''''''''''''''
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
closing = True 'Tells receiving loop to close
receivingClient.Close()
sendingClient.Close()
End Sub
Here are a few other exmples: Here, here, here and here.
Imports System.Threading
Shared client As UdpClient
Shared receivePoint As IPEndPoint
client = New UdpClient(2828) 'Port
receivePoint = New IPEndPoint(New IPAddress(0), 0)
Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))
readThread.Start()
Public Shared Sub WaitForPackets()
While True
Dim data As Byte() = client.Receive(receivePoint)
Console.WriteLine("=" + System.Text.Encoding.ASCII.GetString(data))
End While
End Sub
I'm realizing a .NET chat application but i still have that error:
I can send only a message per connection.
For example. With the code below, i can send only one message that can be received correctly by the other peer, but if i send another message message, on the same connection,it won't be received by the remote PC.
Here is the code:
Dim client_TCP As New TcpClient
Private Sub send_obj(ByVal obj As Object)
Dim bf As New BinaryFormatter
Dim tosend As Packet
tosend.data = obj
bf.Serialize(client_TCP.GetStream(), tosend)
client_TCP.GetStream.Flush()
End Sub
Private Sub connect_to_port()
Try
client_TCP = New TcpClient(client_data.getIP(), client_data.getPort())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub disconnect_from_port()
client_TCP.Close()
End Sub
And here is the listener:
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer.Tick
If client_TCP_listener.Pending = True Then
....
End If
End Sub
So, to send a message I always need to do this (example):
Dim b As Byte
b = 1
disconnect_from_port()
connect_to_port()
client_TCP.GetStream().WriteByte(b)
client_TCP.GetStream().Flush()
I tried to put\remove the flush from both the code. Nothing happened.
Have you got any ideas?!
How do you know that it is not received? Did you try emulating remote host with your own code?
TCP is a stream protocol that means that you can send two bytes doing two separate calls to client_TCP.GetStream().WriteByte(b) and the remote party can receive those 2 bytes using one Receive call. You should not make any assumptions on the I/O API call patterns (number of writes and number of receives) but analyze the data you're sending receiving via stream connection.
So to send messages using stream protocol you have to introduce the notion of the application protocol. For instance [2bytes-size][size-bytes of message] - which means that if we want to send "hello" message we at first will send 2 bytes containing the size of the "hello" string and then the string itself.
make sure that receiving end is also using .net BinaryFormatter for deserlizing the object.