• 0

[VB.NET] In class we made a simple tictactoe program but how do you use tcp


Question

In class we made a simple tictactoe game in vb.net but I wanna try to go the extra mile and make it playable over the network.... I know alot about tcp/ip like I would need to pick one of the computers to host it with a port a number then one of the programs need to be the client and connect to that server.... I remember teaching myself on how to make a simple chat program in vb6 using the winsock ocx but how would I do it in vb.net?

Recommended Posts

  • 0
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx#Y0 so how do I use this code? Where do I put it all? I obviously dont put it all in a command button....
  • 0

No, you could start your TcpListener on the OnLoad() method of the main form. That said, if you're just starting out programming, adding TCP/IP multiplayer to your Tic-Tac-Toe is probably beyond your abilities at the moment. You'll need to define a message format, serialize/deserialize your messages through the connection, ensure synchronisation of all clients, handle disconnects and re-connects gracefully etc. It's not trivial.

  • 0
  On 26/10/2012 at 23:04, Dr_Asik said:

No, you could start your TcpListener on the OnLoad() method of the main form. That said, if you're just starting out programming, adding TCP/IP multiplayer to your Tic-Tac-Toe is probably beyond your abilities at the moment. You'll need to define a message format, serialize/deserialize your messages through the connection, ensure synchronisation of all clients, handle disconnects and re-connects gracefully etc. It's not trivial.

copy and paste it onload and it dont work and the message part is easy just alot of ifs "if client sends "X:1"" Put an x mark on button 1 so on.....

  • 0
  On 27/10/2012 at 10:37, togermano said:

copy and paste it onload and it dont work and the message part is easy just alot of ifs "if client sends "X:1"" Put an x mark on button 1 so on.....

How does it not work? What do you expect it to do? Do you have a client as well? A listener is just that, a listener, it listens to incoming connections. You need one instance of your app that acts as the server and one (or multiple others) that act as the client. There's a link to an example TcpClient in that same tutorial page for TcpListener. Read up on tcp connections, how to establish a connection, how to pass messages around, how to close the connection.

"A lot of ifs" is a terrible way of going about this btw. What would you do for a 10x10 tic-tac-toe? Code 100 if-elses? What if you wanted to support multiple different sizes? If you don't know about lists and loops I don't think there's any way you're going to add multiplayer functionality. Start one step at a time.

  • 0
  On 28/10/2012 at 01:28, Dr_Asik said:

How does it not work? What do you expect it to do? Do you have a client as well? A listener is just that, a listener, it listens to incoming connections. You need one instance of your app that acts as the server and one (or multiple others) that act as the client. There's a link to an example TcpClient in that same tutorial page for TcpListener. Read up on tcp connections, how to establish a connection, how to pass messages around, how to close the connection.

"A lot of ifs" is a terrible way of going about this btw. What would you do for a 10x10 tic-tac-toe? Code 100 if-elses? What if you wanted to support multiple different sizes? If you don't know about lists and loops I don't think there's any way you're going to add multiplayer functionality. Start one step at a time.

The code errors when I try to run it..... I am not stupid when it comes to this stuff i have used winsock before i Know i need a client and a server I took a ccna class all about tcp/ip

  • 0
  On 29/10/2012 at 11:29, togermano said:

What isnt an error?

First off, move your "imports" lines above the Public Class Form1 - they need to stay first in the code document.

Then remove the class MyTcpListener, and the public shared main sub - they do not belong inside another Sub/Function/Method.

Next you will figure out that this code has an endless loop that will basicly lock up your program as soon as it starts (it will never stop "loading"). You need to either put this code in a separate thread or use the TcpListener asynchronously (spelling?)

Have a look at http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.beginacceptsocket(v=vs.90).aspx#Y0 for examples

  • 0

Your code doesn't compile. It's not valid Visual Basic and Visual Studio should show you some error messages in its output and error windows when you attempt to start the program. These error messages can often tell you what the problems are and how to fix them.

- The Imports directives should go at the top of the file, not inside a class declaration

- Your MyTcpListener class is declared inside the Form1 class, which is illegal - move it after the "End Class" of Form1 or, better, to its own file

- You're declaring a Main() function inside MyTcpListener, but your project is probably a Windows Forms Application, which already has its own Main() function - a .NET program must have only one Main() function.

- The code that goes inside that Main() method should go in the OnLoad() method of the Form1 class, as I explained to you before

Do you even know what is a class, a module, a namespace, what do access modifiers do, how to override a virtual method, what are events, how to register/unregister to them, what's a Shared method vs non-Shared, what is the purpose of the Main() method, etc? Implementing multiplayer will require putting together several pieces which you seem to ignore the very nature of. It's not like you're going to copy-paste the correct code here and there and it's all magically going to work; even if it did, that wouldn't be very useful to you, would it? Start by properly learning Visual Basic and the .NET Base Class Library and then you'll be able to implement advanced functionality like this and understand what you're doing. Learn to walk before you run...

  • 0
  On 08/11/2012 at 22:13, togermano said:

thanks everyone and yes it is in an endless loop how do I put it in its own thread?

Put that code in its own method and pass the method as a delegate to a BackgroundWorker. There are many more options for threading in .NET but that's probably the simplest one here.
  • 0
  On 28/10/2012 at 01:28, Dr_Asik said:

How does it not work? What do you expect it to do? Do you have a client as well? A listener is just that, a listener, it listens to incoming connections. You need one instance of your app that acts as the server and one (or multiple others) that act as the client. There's a link to an example TcpClient in that same tutorial page for TcpListener. Read up on tcp connections, how to establish a connection, how to pass messages around, how to close the connection.

"A lot of ifs" is a terrible way of going about this btw. What would you do for a 10x10 tic-tac-toe? Code 100 if-elses? What if you wanted to support multiple different sizes? If you don't know about lists and loops I don't think there's any way you're going to add multiplayer functionality. Start one step at a time.

Currently I got it working that when I write something in a telnet client and using IFs it will trigger a msgbox depending on what I wrote into the telnet client. You say ifs a terrible way to do it then what is a good way to do it?

  • 0

For instance, if your messages are text messages of the form "1,2" where 1 and 2 are the line and column to play at, you could put all your textboxes in a two-dimensional array, parse the message as two integers, and use these as indexes into the array to obtain the corresponding textbox. No need for any ifs, works with any board size.

  • 0

Thanks! I may try to do it the if way and then try it with your way after

I ran into another problem I can't access any of form1s command buttons from the tcp/ip thread I have tried using form1.label1.text = "connected!!" it doesnt error but it doesnt work either. I googled the problem but none of it was any help

http://stackoverflow.com/questions/5683724/problem-accessing-a-textbox-control-from-another-class-thread-in-vb-net

  • 0

You're not allowed to update the UI from any other thread than the UI thread. Use the Invoke (synchronous) or BeginInvoke (asynchronous) method of the main form to pass UI updates (as delegates) from a background thread.

  • 0
  On 10/11/2012 at 17:30, Dr_Asik said:

You're not allowed to update the UI from any other thread than the UI thread. Use the Invoke (synchronous) or BeginInvoke (asynchronous) method of the main form to pass UI updates (as delegates) from a background thread.

Is there a sample of that somewhere?

  • 0

Public Shared Sub ticserver()

server = Nothing

Try

CheckForIllegalCrossThreadCalls = False

' Set the TcpListener on port 13000.

Dim port As Int32 = 13000

Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1

server = New TcpListener(localAddr, port)

' Start listening for client requests.

server.Start()

' Buffer for reading data

Dim bytes(1024) As Byte

Dim data As String = Nothing

' Enter the listening loop. While True

Console.Write("Waitinga connection... ")

' Perform a blocking call to accept requests. ' You could also user server.AcceptSocket() here.

client = server.AcceptTcpClient()

Console.WriteLine("Connected!")

Form1.PictureBox1.Show()

Form1.Label1.Text = "A client has connected to you"

Form1.Label1.Show()

data = Nothing

' Get a stream object for reading and writing

stream = 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)

Console.WriteLine("Received: {0}", data)

' Process the data sent by the client.

data = data.ToUpper()

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()

' Console.WriteLine("SocketException: {0}", e)

Finally

server.Stop()

End Try

Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")

Console.Read()

End Sub 'MainEnd Class'MyTcpListener

according to this http://tech.xster.ne...eads-on-vb-net/ adding the code

Me.CheckForIllegalCrossThreadCalls = False

should make it work but it doesnt..... why does me. always error I remove it and the error is gone but still this code does nothing

"

Form1.PictureBox1.Show()

Form1.Label1.Text = "A client has connected to you"

Form1.Label1.Show()

data = Nothing"

  • 0
  On 10/11/2012 at 19:01, togermano said:

Is there a sample of that somewhere?

Of course, googling any of the terms I mentionned will return you hundreds of useful results.

Don't disable checking for illegal cross-thread calls. You're making an illegal cross-thread call, disabling checking won't make it any less illegal.

  • 0
  On 10/11/2012 at 20:05, togermano said:

I dont get any of the codes they all use me.whatever and that always causes an error

"Me" is a reference to the current object, for instance if your code is inside your main Form class (like most tutorials assume), then "Me" is a reference to the Form object, which has an Invoke and a BeginInvoke method. Since I suppose you segregated your background thread code to another class, you'll have to pass it a reference to the Form object in order to invoke any methods of the Form from it. Alternatively, you could simply bring that code back to the main Form class and you'd be able to use "Me" to reference to Form then.
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Wonder if the HDMI Forum will allow AMD to use HDMI 2.2 under Linux.
    • Where did you hear visio is discontinued? It's still available and being updated on Office 365 and even has an online free version now too.. and dont tell me because visio 2021 has EOL listed a Oct 13, 2026.. they have a beta version right now for visio 2026
    • PC gaming is stalling as well, recent analyst post I read is that it will stall for at least two years because of prices, tariffs and AI demand impacting GPU cost and availability. So far the only console to go up in price has been the Xbox. Which IMHO is just part of Microsoft’s plans to get out of the traditional insole market and move to a “Xbox” console that is just a PC made by an OEM with a Xbox sticker on it.
    • Jumping unicorns means people initiate Nintendo gaming
    • KB5060829: Microsoft makes Windows 11 File Explorer, Search faster with Build 26100.4482 by Sayan Sen Microsoft has released a new Release Preview build for Windows 11 Insiders. The new build, 26100.4482, under KB5060829, improves the performance of the File Explorer in case of extracting archives. The company says "has been enhanced when extracting archive files" and that the improvement will mainly be felt "in the case of copy pasting large numbers of files out of large 7z or .rar archives." Aside from File Explorer, Microsoft says that users can also expect a snappier Search. Microsoft notes that earlier the feature would respond "very slowly—the Search Box can take over 10 seconds to load before you can use it." Besides those, Taskbar has also received an improvement as it will better use the available real estate space more effectively with new ability to resize icons so more apps can fit. The build also brings new PC Migration tool. Start menu pins have also changed You can view the full changelog below: Gradual rollout [App defaults] New! We are rolling out some small changes in the EEA region for default browsers via the Set default button in Settings > Apps > Default apps: Additional file and link types will be set for the new default browser, if it registers them. The new default browser will be pinned to the Taskbar and Start menu unless you choose not to pin it by clearing the checkboxes. There is now a separate one-click button for browsers to change your .pdf default, if the browser registers for the .pdf file type. [Start menu] New! For Admins, the Configure Start Pins policy now includes an option to apply Start menu pins only once. This means users will receive the admin Start menu pins on their first sign-in (day 0), but afterward, they can personalize their pinned layout, and those changes will be retained. This policy can also be applied through group policy, in addition to the existing configuration service provider (CSP) method. [Taskbar & System Tray] New! The taskbar now resizes icons to fit more apps when space runs low, keeping everything visible and easy to access. You can adjust how icons appear in settings—reduce icon size only when the taskbar is full (default), keep icons at their original size at all times by selecting Never, or use smaller icons all the time by selecting Always. To change this setting, right-click an empty area on the taskbar, select Taskbar settings, expand the Taskbar behaviors section, and choose your preference under Show smaller taskbar buttons. New! In addition to the new grouping of the Accessibility menu in Quick settings, there are text descriptions for the assistive technologies like Narrator, Voice access, and more for easier identification and learning. New! Adjusted the indicator (pill) under taskbar apps to make it wider and more visible. Fixed: Clicking the top third of the buttons in the top row doesn’t work to enable or disable the button. Fixed: WIN + CTRL + Number doesn’t work anymore for switching windows of an open app in the taskbar Fixed: When using taskbar in Windows, the media controls that appear in the preview windows for apps might unexpectedly flicker. [Windows Share] New! When you share links or web content using the Windows share window, you will see a visual preview for that content. New! In the Windows share window, you can select a compression level—High, Medium, or Low Quality—when editing and sharing images, instead of selecting from a 0–100 scale. [PC Migration] We’re beginning the rollout of a new PC-to-PC migration experience in Windows. You’ll start to see the landing and the pairing page in the Windows Backup app, giving you a first look at what’s coming. In the full experience, you will be able to transfer your files and settings from your old PC to the new one during the PC setup process. Support during the PC setup will be available in a future update. We are releasing in phases for a smooth experience and will provide more details soon. [File Explorer] Improved: Performance has been enhanced when extracting archive files – this will particularly help in the case of copy pasting large numbers of files out of large 7z or .rar archives. Narrator New! The Screen Curtain feature in Narrator helps protect your privacy and improve focus by blacking out the screen while Narrator reads content aloud. This is especially helpful in public or shared spaces, where you can work with sensitive information without others seeing your screen. To turn on Narrator, press Ctrl + Windows + Enter. Then press Caps Lock + Ctrl + C to enable Screen Curtain. While it’s on, you can use Narrator as usual with the screen hidden. Press Caps Lock + Ctrl + C again to turn it off. New! Narrator makes it easier to discover and learn about its features directly within the experience. Whether you’re new or exploring advanced options, Narrator will guide you through the latest updates using a series of steps and prompts that explain each new feature and change. [Voice Access] New! You can now use voice access to navigate, dictate, and interact with Windows using voice commands in Simplified Chinese and Traditional Chinese. New! You can add custom words to the dictionary in voice access. The feature will be available in all the currently supported voice access languages. [Settings] New! The Settings homepage on PCs managed by IT administrators now includes cards tailored for enterprise use. These include familiar options like “Recommended settings” and “Bluetooth devices,” along with two cards for device info and accessibility preferences. If a user signs in with both a work or school account and a Microsoft account, an additional accounts card appears to show both account types. New! Added the country or region selected during device setup under Settings > Time & language > Language & region. Fixed: The storage card in Settings > System > About shows an incorrect or unreadable character instead of the proper disk size. [Windowing] Fixed: When you ALT + Tab out of a full screen game, other windows (like Windows Terminal might stop responding. Fixed: An underlying issue might lead to unexpected window size and position changes after sleep/resume for some devices. Fixed: Explorer.exe might stop working unexpectedly when dragging a window if window snapping is enabled. [Scripting] Fixed: Running a script on a remote SMB share might take an unexpectedly long time if the share was an older Windows Server version like Windows Server 2019. [Graphics] Improved: Made some underlying changes to help improve display related user experiences, including reducing screen flashing in some display configuration transitions and removing unnecessary display resets which was happening in some cases. Fixed: Certain displays might be unexpectedly green. Fixed: If User Account Control (UAC) is set to Always Notify and the button under Settings > System > Display for color calibration is selected for your display and canceled, Settings will stop responding. [Color Filters] Improved: Adjusted the location of the intensity and color boost sliders under Settings > Accessibility > Color Filters, so the color previews at the top of the page are visible while adjusting the sliders. [Input] Fixed: Typing Japanese with the touch keyboard may stop working after switching to typing with an English keyboard and back. [Printing] Fixed: Printed lines might be unexpectedly thicker than expected. [MSFTEdit.dll] Fixed: Some apps like Sticky Notes and dxdiag might stop working when the display language is set to Arabic or Hebrew. Normal rollout [Copilot] Fixed: Improved the Copilot key’s reliability and resolved an issue that prevented users from restarting Copilot after using the key. [Performance] Fixed: This update addresses an issue to maintain efficiency of Storage Spaces Direct (S2D). When running complex software defined data center (SDDC) related workflows, it’s possible the system might become unresponsive. [Storage optimization] Fixed: An issue that prevented unused language packs and Feature on Demand packages from being fully removed, which led to unnecessary storage use and longer Windows Update installation times. [Windows Search] Fixed: Windows Search responds very slowly—the Search Box can take over 10 seconds to load before you can use it. Fixed: This update enhances the reliability of Windows Search and resolves an issue that prevented users from typing in Windows Search in some cases. You can find the official blog post here on Microsoft's website.
  • Recent Achievements

    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
    • Week One Done
      Karan Khanna earned a badge
      Week One Done
    • First Post
      MikeK13 earned a badge
      First Post
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      690
    2. 2
      ATLien_0
      264
    3. 3
      Michael Scrip
      201
    4. 4
      +FloatingFatMan
      167
    5. 5
      Steven P.
      137
  • Tell a friend

    Love Neowin? Tell a friend!