Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Sunday, March 1, 2009

WCF Host and Client in same assembly

A few weeks ago I decided to write a networked, multi-player version of Sudoku. One of the first things I had to decide to tackle was how the client and server should communicate. I had done something similar in the .net framework 1.1 using sockets and that was my first thought, however I had heard of .NET remoting and thought that was worth looking into. After some research, I found that the most current practice for client/server communication was to use WCF, part of the .NET Framework 3.0 and thereafter. I could not believe how simple this ended up being, and it broke down to a few lines of code in the end. First I had to put this section in my app.config:


















For service name I just put the name of my class with the namespace, I gave the name of the service the same name as my class, and as my contract, I created an interface that has to be present in the server and client, but in my case my assembly could be either. The interface just specified which methods could be called on my server class, and then my server class just implemented that interface. For the server I added a thread to my user interface and when a user chose to host a game it just did this:

mHostThread = New Threading.Thread(AddressOf StartHost)
mHostThread.Start()

And startHost simply did this:

mPuzzleHost = New ServiceHost(GetType(PuzzleServer))
mPuzzleHost.Open()

Having this in a thread allowed the person hosting the game to also join as a client. Then to join the game (server) as client all I had to do was this:

Dim puzzleFactory As ChannelFactory(Of IPuzzleServer) = New ChannelFactory(Of IPuzzleServer)("PuzzleServer")
puzzleFactory.Endpoint.Address = New System.ServiceModel.EndpointAddress("net.tcp://" & frm.IP & ":3315/PuzzleServer")

Try
mPuzzleProxy = puzzleFactory.CreateChannel
mPlayerId = mPuzzleProxy.JoinGame(frm.PlayerName, frm.PlayerColor)
Catch ex As Exception
MessageBox.Show("Could not connect to host '" & frm.IP & "'. Reason: " & ex.Message)
Exit Sub
End Try

I hope that makes sense, if you have any questions feel free to email me.