StreamReader/Writer Events?

Weebs

New member
Joined
Mar 21, 2008
Messages
1
Programming Experience
1-3
As a project in my Computer Science class at school, I've chosen to develop the board game Battleship. I've decided to add the multi-player component by having two players verse each other via network. I've just stubbed-out all my code so it runs through the turn sequences and message boxes just showing what would go on in each function/sub procedure and everything worked fine. I've now begun writing the actual code for the game, and I've gotten an algorithm thought out for most of the game, but one thing I'm running into problems with is telling the other player when your board is setup. I've added code so that the game starts up, you specify whether you want to host or connect to a game, and code to establish a connection between the host and client. I just can't think of to make it so say, once a player is setting up the board they click a done button and it sends a message to the other player, because the other player can only listen for messages if StreamReader.ReadLine() is being called, but if it is the other player cannot setup their board while it is. Is there a way that I can make it so that there's almost event-like code for the sockets? So that everytime one player sends data the other player's StreamReader will call ReadLine?
 
The Socket class uses an asynchronous programming model. You call BeginReceive and pass a reference to a method. When data is received that method is executed. It's very similar to an event-driven model but more explicit. When the callback method you specify is executed, then you can read the data that was just received. E.g.
VB.NET:
Private Sub Receive()
    Me.sock.BeginReceive(Buffer, Offset, Size, SocketFlags.None, AddressOf Read)
End Sub

Private Sub Read(ByVal ar As IAsyncResult)
    Me.sock.EndReceive(ar)

    'Read data from sock here.
End Sub
 
Back
Top