Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a.

Similar presentations


Presentation on theme: " 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a."— Presentation transcript:

1  2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a Simple Server (Using Stream Sockets) 22.3 Establishing a Simple Client (Using Stream Sockets) 22.4 Client/Server Interaction via Stream Socket Connections 22.5 Connectionless Client/Server Interaction via Datagrams 22.6 Client/Server Tic-Tac-Toe Using a Multithreaded Server

2  2002 Prentice Hall. All rights reserved. 2 22.1 Introduction Client-server relationship –The client requests some actions to be performed; server performs the action and responds to the client System.Net.Sockets –Socket-based communications Enable developers to view networking as if it were file I/O Employ stream sockets –Stream Sockets provide a connection-oriented service like Transmission Control Protocol (TCP) –Sockets Sockets are fundamental way to perform network communication in the.NET Framework

3  2002 Prentice Hall. All rights reserved. 3 22.2 Establishing a Simple Server (Using Stream Sockets) Step 1: Create an object of class TcpListener –TcpListener belongs to a namespace System.Net.Sockets –TcpListener assigns the server to port number (IP Address) Step 2: Call TcpListener’s Start method –Start method causes TcpListener object to begin listening for connection requests Step 3: Makes connection between server & client –Socket connection = Server.AcceptSocket( ) Step 4: Processing Phase Step 5: Connection Termination Phase

4  2002 Prentice Hall. All rights reserved. 4 22.3 Establishing a Simple Client (Using Stream Sockets) Step 1: Create Object of class TcpClient –Method Connect of class TcpClient calls method Connect of class Socket to establish the connection Step 2: Uses GetStream to get NetworkStream –Methods WriteByte and Write can be used to output individual bytes or sets of bytes to the server Step 3: Processing phase –Client uses methods Read, ReadByte, Write, and WriteByte of class NetworkStream to perform communications Step 4: Close connection

5  2002 Prentice Hall. All rights reserved. 5 22.4 Client/Server Interaction via Stream- Socket Connection Client/server chat application –Server waits for client’s request to make a connection –Both client and server applications contain Textboxes the enhance users to type messages and send them away –Message “TERMINATE” disconnects the connection between the client and the server

6  2002 Prentice Hall. All rights reserved. Outline 6 Server.vb 1 ' Fig. 22.1: Server.vb 2 ' Set up a Server that receives connections from clients and sends 3 ' String data to clients. 4 5 Imports System.Windows.Forms 6 Imports System.Threading 7 Imports System.Net.Sockets 8 Imports System.IO 9 10 Public Class FrmServer 11 Inherits Form 12 13 ' TextBoxes for receiving user input and displaying information 14 Friend WithEvents txtInput As TextBox 15 Friend WithEvents txtDisplay As TextBox 16 17 Private connection As Socket ' Socket object handles connection 18 Private readThread As Thread ' server thread 19 20 ' Stream through which to transfer data 21 Private socketStream As NetworkStream 22 23 ' objects for writing and reading data 24 Private writer As BinaryWriter 25 Private reader As BinaryReader 26 27 Public Sub New() 28 MyBase.New() 29 30 ' equired by the Windows Form Designer. 31 InitializeComponent() 32 33 ' add any initialization after the 34 ' InitializeComponent call 35

7  2002 Prentice Hall. All rights reserved. Outline 7 Server.vb 36 ' create thread from server 37 readThread = New Thread(AddressOf RunServer) 38 readThread.Start() 39 End Sub ' New 40 41 ' Visual Studio.NET generated code 42 43 ' invoked when user closes server 44 Private Sub FrmServer_Closing( _ 45 ByVal sender As System.Object, _ 46 ByVal e As system.ComponentModel.CancelEventArgs) _ 47 Handles MyBase.Closing 48 49 System.Environment.Exit(System.Environment.ExitCode) 50 End Sub ' FrmServer_Closing 51 52 ' send server text to client 53 Private Sub txtInput_KeyDown( ByVal sender As System.Object, _ 54 ByVal e As system.Windows.Forms.KeyEventArgs) _ 55 Handles txtInput.KeyDown 56 57 ' send text to client 58 Try 59 60 ' send text if user pressed Enter and connection exists 61 If (e.KeyCode = Keys.Enter AndAlso _ 62 Not connection Is Nothing) Then 63 64 writer.Write("SERVER>>> " & txtInput.Text) ' send data 65 66 txtDisplay.Text &= vbCrLf & "SERVER>>> " & _ 67 txtInput.Text 68 Creates a Thread that accepts connections from clients Starts the Thread Reads the String and sends it via method write of class BinaryWriter Defines FrmServer_Closing event handler for the Closing event

8  2002 Prentice Hall. All rights reserved. Outline 8 Server.vb 69 ' close connection if server’s user signals termination 70 If txtInput.Text = "TERMINATE" Then 71 connection.Close() 72 End If 73 74 txtInput.Clear() 75 End If 76 77 ' handle exception if error occurs when server sends data 78 Catch exception As SocketException 79 txtDisplay.Text &= vbCrLf & "Error writing object" 80 81 End Try 82 83 End Sub ' txtInput_KeyDown 84 85 ' allow client to connect and display text sent by user 86 Public Sub RunServer() 87 Dim listener As TcpListener 88 Dim counter As Integer = 1 89 90 ' wait for request, then establish connection 91 Try 92 93 ' Step 1: create TcpListener 94 listener = New TcpListener(5000) 95 96 ' Step 2: TcpListener waits for connection request 97 listener.Start() 98 99 ' Step 3: establish connection upon client request 100 While True 101 txtDisplay.Text = "Waiting for connection" & vbCrLf 102 Declares TcpListener to listen for a connection request from a client at port 5000 Invokes method Start of TcpListener object Calls method Close of the Socket object to close the connection

9  2002 Prentice Hall. All rights reserved. Outline 9 Server.vb 103 ' accept an incoming connection 104 connection = listener.AcceptSocket() 105 106 ' create NetworkStream object associated with socket 107 socketStream = New NetworkStream(connection) 108 109 ' create objects for transferring data across stream 110 writer = New BinaryWriter(socketStream) 111 reader = New BinaryReader(socketStream) 112 113 txtDisplay.Text &= "Connection " & counter & _ 114 " received." & vbCrLf 115 116 ' inform client that connection was successfull 117 writer.Write("SERVER>>> Connection successful") 118 119 txtInput.ReadOnly = False 120 Dim theReply As String = "" 121 122 ' Step 4: read String data sent from client 123 Try 124 125 ' loop until client signals termination 126 Do 127 theReply = reader.ReadString() ' read data 128 129 ' display message 130 txtDisplay.Text &= vbCrLf & theReply 131 132 Loop While (theReply <> "CLIENT>>> TERMINATE" _ 133 AndAlso connection.Connected) 134 135 ' handle exception if error reading data 136 Catch inputOutputException As IOException 137 MessageBox.Show("Client application closing") Calls method AcceptSocket of the TcpListener object Passes the Socket object as an argument to the constructor of a NetworkStream object Creates instances of BinaryWriter and BinaryReader classes Append text to the TextBox indicating that connection was received Do/Loop While executes until server receives termination message Uses BinaryReader method ReadSring to read a String from the stream

10  2002 Prentice Hall. All rights reserved. Outline 10 Server.vb 138 139 ' close connections 140 Finally 141 142 txtDisplay.Text &= vbCrLf & _ 143 "User terminated connection" 144 145 txtInput.ReadOnly = True 146 147 ' Step 5: close connection 148 writer.Close() 149 reader.Close() 150 socketStream.Close() 151 connection.Close() 152 153 counter += 1 154 End Try 155 156 End While 157 158 ' handle exception if error occurs in establishing connection 159 Catch inputOutputException As IOException 160 MessageBox.Show("Server application closing") 161 162 End Try 163 164 End Sub ' RunServer 165 166 End Class ' FrmServer Close the BinaryWriter, BinaryReader, NetworkStream and Socket

11  2002 Prentice Hall. All rights reserved. Outline 11 Client.vb 1 ' Fig. 22.2: Client.vb 2 ' Set up a client that reads and displays data sent from server. 3 4 Imports System.Windows.Forms 5 Imports System.Threading 6 Imports System.Net.Sockets 7 Imports System.IO 8 9 Public Class FrmClient 10 Inherits Form 11 12 ' TextBoxes for inputting and displaying information 13 Friend WithEvents txtInput As TextBox 14 Friend WithEvents txtDisplay As TextBox 15 16 ' stream for sending data to server 17 Private output As NetworkStream 18 19 ' objects for writing and reading bytes to streams 20 Private writer As BinaryWriter 21 Private reader As BinaryReader 22 23 Private message As String = "" ' message sent to server 24 25 ' thread prevents client from blocking data transfer 26 Private readThread As Thread 27 28 Public Sub New() 29 MyBase.New() 30 31 ' equired by the Windows Form Designer. 32 InitializeComponent() 33 34 ' add any initialization after the 35 ' InitializeComponent call

12  2002 Prentice Hall. All rights reserved. Outline 12 Client.vb 36 37 readThread = New Thread(AddressOf RunClient) 38 readThread.Start() 39 End Sub ' New 40 41 ' Visual Studio.NET generated code 42 43 ' invoked when user closes application 44 Private Sub FrmClient_Closing(ByVal sender As System.Object, _ 45 ByVal e As System.ComponentModel.CancelEventArgs) _ 46 Handles MyBase.Closing 47 48 System.Environment.Exit(System.Environment.ExitCode) 49 End Sub 50 51 ' send user input to server 52 Private Sub txtInput_KeyDown(ByVal sender As System.Object, _ 53 ByVal e As System.windows.Forms.KeyEventArgs) _ 54 Handles txtInput.KeyDown 55 56 ' send user input if user pressed Enter 57 Try 58 59 ' determine whether user pressed Enter 60 If e.KeyCode = Keys.Enter Then 61 62 ' send data to server 63 writer.Write("CLIENT>>> " & txtInput.Text) 64 65 txtDisplay.Text &= vbCrLf & "CLIENT>>> " & _ 66 txtInput.Text 67 68 txtInput.Clear() 69 End If 70 The client object creates a Thread in its constructor to handle all incoming messages The event handler txtInput_KeyDown reads the String from the TextBox and sends it via BinaryWriter method Write

13  2002 Prentice Hall. All rights reserved. Outline 13 Client.vb 71 ' handle exception if error occurs in sending data to server 72 Catch exception As SocketException 73 txtDisplay.Text &= vbCrLf & "Error writing object" 74 End Try 75 76 End Sub ' txtInput_KeyDown 77 78 ' connect to server and display server-generated text 79 Public Sub RunClient() 80 Dim client As TcpClient 81 82 ' instantiate TcpClient for sending data to server 83 Try 84 85 txtDisplay.Text &= "Attempting connection" & vbCrLf 86 87 ' Step 1: create TcpClient and connect to server 88 client = New TcpClient() 89 client.Connect("localhost", 5000) 90 91 ' Step 2: get NetworkStream associated with TcpClient 92 output = client.GetStream() 93 94 ' create objects for writing and reading across stream 95 writer = New BinaryWriter(output) 96 reader = New BinaryReader(output) 97 98 txtDisplay.Text &= vbCrLf & "Got I/O streams" & vbCrLf 99 100 txtInput.ReadOnly = False 101 102 ' Step 3: processing phase 103 Try 104 Method RunClient connects, receives and sends data to and from the Server Declares TcpClient object Invokes method Connect to establish connection The client obtains NetworkStream through a call to TcpClient method GetStream

14  2002 Prentice Hall. All rights reserved. Outline 14 Client.vb 105 ' loop until server signals termination 106 Do 107 108 ' read message from server 109 message = reader.ReadString 110 txtDisplay.Text &= vbCrLf & message 111 112 Loop While message <> "SERVER>>> TERMINATE" 113 114 ' handle exception if error in reading server data 115 Catch inputOutputException As IOException 116 MessageBox.Show("Client application closing") 117 118 ' Step 4: close connection 119 Finally 120 121 txtDisplay.Text &= vbCrLf & "Closing connection." & _ 122 vbCrLf 123 124 writer.Close() 125 reader.Close() 126 output.Close() 127 client.Close() 128 129 End Try 130 131 Application.Exit() 132 133 ' handle exception if error in establishing connection 134 Catch inputOutputException As Exception 135 MessageBox.Show("Client application closing") 136 137 End Try 138 Do/Loop While executes until server receives termination message Uses BinaryReader method ReadString to obtain the next message from the server Displays the message “Closing connection” Close BinaryWriter, BinaryReader, NetworkStream and TcpClient objects

15  2002 Prentice Hall. All rights reserved. Outline 15 Client.vb 139 End Sub ' RunClient 140 141 End Class ' FrmClient

16  2002 Prentice Hall. All rights reserved. Outline 16 Client.vb

17  2002 Prentice Hall. All rights reserved. Outline 17 Client.vb

18  2002 Prentice Hall. All rights reserved. 18 22.5 Connectionless Client/Server Interaction via Datagrams Connectionless Transmission via Datagrams –Bundles and sends information via datagrams Information is broken into several pieces if it is too big Information might arrive in order, out of order or not at all

19  2002 Prentice Hall. All rights reserved. Outline 19 Server.vb 1 ' Fig. 22.3: Server.vb 2 ' Server receives packets from a client, then echoes packets back 3 ' to clients. 4 5 Imports System.Windows.Forms 6 Imports System.Net 7 Imports System.Net.Sockets 8 Imports System.Threading 9 10 Public Class FrmDatagramServer 11 Inherits Form 12 13 ' TextBox displays packet information 14 Friend WithEvents txtDisplay As TextBox 15 16 ' reference to client that will send packet information 17 Private client As UdpClient 18 19 ' client IP address/port number pair 20 Private receivePoint As IPEndPoint 21 22 Public Sub New() 23 MyBase.New() 24 25 ' equired by the Windows Form Designer. 26 InitializeComponent() 27 28 ' add any initialization after the 29 ' InitializeComponent call 30 31 ' instantiate UdpClient listening for requests at port 5000 32 client = New UdpClient(5000) 33 34 ' hold IP address and port number of client 35 receivePoint = New IPEndPoint(New IPAddress(0), 0) Creates an instance of the UdpClient class that receives data at port 5000 Creates an instance of class IPEndPoint to hold IP address and port number of client(s) that transmit to Server

20  2002 Prentice Hall. All rights reserved. Outline 20 Server.vb 36 37 Dim readThread As Thread = New Thread _ 38 (New ThreadStart(AddressOf WaitForPackets)) 39 40 readThread.Start() ' wait for packets 41 End Sub ' New 42 43 ' Visual Studio.NET generated code 44 45 ' invoked when user closes server 46 Protected Sub Server_Closing(ByVal sender As system.Object, _ 47 ByVal e As System.ComponentModel.CancelEventArgs) _ 48 Handles MyBase.Closing 49 50 System.Environment.Exit(System.Environment.ExitCode) 51 End Sub ' Server_Closing 52 53 ' wait for packets to arrive from client 54 Public Sub WaitForPackets() 55 56 ' use infinite loop to wait for data to arrive 57 While True 58 59 ' receive byte array from client 60 Dim data As Byte() = client.Receive(receivePoint) 61 62 ' output packet data to TextBox 63 txtDisplay.Text &= vbCrLf & "Packet received:" & _ 64 vbCrLf & "Length: " & data.Length & vbCrLf & _ 65 "Containing: " & _ 66 System.Text.Encoding.ASCII.GetString(data) 67 68 txtDisplay.Text &= vbCrLf & vbCrLf & _ 69 "Echo data back to client..." 70 Method Receive receives a byte array from the client Update the Server’s display to include the packet’s information and content

21  2002 Prentice Hall. All rights reserved. Outline 21 Server.vb 71 ' echo information from packet back to client 72 client.Send(data, data.Length, receivePoint) 73 txtDisplay.Text &= vbCrLf & "Packet sent" & _ 74 vbCrLf 75 76 End While 77 78 End Sub ' WaitForPackets 79 80 End Class ' FrmDatragramServer Echoes the data back to the client using UdpClient method Send

22  2002 Prentice Hall. All rights reserved. Outline 22 Client.vb 1 ' Fig. 22.4: Client.vb 2 ' Client sends packets to, and receives packets from, a server. 3 4 Imports System.Windows.Forms 5 Imports System.Net 6 Imports System.Net.Sockets 7 Imports System.Threading 8 9 Public Class FrmDatagramClient 10 Inherits Form 11 12 ' TextBoxes for inputting and displaying packet information 13 Friend WithEvents txtInput As TextBox 14 Friend WithEvents txtDisplay As TextBox 15 16 ' UdpClient that sends packets to server 17 Private client As UdpClient 18 19 ' hold IP address and port number of clients 20 Private receivePoint As IPEndPoint 21 22 Public Sub New() 23 MyBase.New() 24 25 ' equired by the Windows Form Designer. 26 InitializeComponent() 27 28 ' add any initialization after the 29 ' InitializeComponent() call 30 31 receivePoint = New IPEndPoint(New IPAddress(0), 0) 32 33 ' instantiate UdpClient to listen on port 5001 34 client = New UdpClient(5001) 35 Declares UdpClient object to receive packets at the port 5001

23  2002 Prentice Hall. All rights reserved. Outline 23 Client.vb 36 Dim thread As Thread = New Thread _ 37 (New ThreadStart(AddressOf WaitForPackets)) 38 39 thread.Start() ' wait for packets 40 End Sub ' New 41 42 ' Visual Studio.NET generated code 43 44 ' invoked when user closes client 45 Private Sub FrmDatagramClient_Closing( _ 46 ByVal sender As System.Object, _ 47 ByVal e As System.ComponentModel.CancelEventArgs) _ 48 Handles MyBase.Closing 49 50 System.Environment.Exit(System.Environment.ExitCode) 51 End Sub ' FrmDatagramClient_Closing 52 53 ' invoked when user presses key 54 Private Sub txtInput_KeyDown( ByVal sender As System.Object, _ 55 ByVal e As System.Windows.Forms.KeyEventArgs) _ 56 Handles txtInput.KeyDown 57 58 ' determine whether user pressed Enter 59 If e.KeyCode = Keys.Enter Then 60 61 ' create packet (datagram) as String 62 Dim packet As String = txtInput.Text 63 64 txtDisplay.Text &= vbCrLf & _ 65 "Sending packet containing: " & packet 66 67 ' convert packet to byte array 68 Dim data As Byte() = _ 69 System.Text.Encoding.ASCII.GetBytes(packet) 70 Convert the String that the user entered in the TextBox to Byte array

24  2002 Prentice Hall. All rights reserved. Outline 24 Client.vb 71 ' send packet to server on port 5000 72 client.Send(data, data.Length, "localhost", 5000) 73 74 txtDisplay.Text &= vbCrLf & "Packet sent" & vbCrLf 75 txtInput.Clear() 76 End If 77 78 End Sub ' txtInput_KeyDown 79 80 ' wait for packets to arrive 81 Public Sub WaitForPackets() 82 83 While True 84 85 ' receive byte array from client 86 Dim data As Byte() = client.Receive(receivePoint) 87 88 ' output packet data to TextBox 89 txtDisplay.Text &= vbCrLf & "Packet received:" & _ 90 vbCrLf & "Length: " & data.Length & vbCrLf & _ 91 System.Text.Encoding.ASCII.GetString(data) 92 93 End While 94 95 End Sub ' WaitForPackets 96 97 End Class ' FrmDatagramClient Invokes UdpClient method Send to send the Byte array to the Server that is located on the localhost Uses an infinite loop to wait for these packets UdpClient method Receive blocks until a packet of data is received Displays the message in the TextBox “packet received” when packet arrives

25  2002 Prentice Hall. All rights reserved. Outline 25 Client.vb

26  2002 Prentice Hall. All rights reserved. 26 22.6 Client/Server Tic-Tac-Toe Using a Multithreaded Server Stream Sockets and Client/Server Techniques –FrmServer allows the FrmClients to connect to server and play Tic-Tac-Toe –Throughout the game, the server maintains information regarding the status of the board so that the server can validate players requested moves –Neither the player nor the client can establish whether a payer has won the game

27  2002 Prentice Hall. All rights reserved. Outline 27 Server.vb 1 ' Fig. 22.5: Server.vb 2 ' Server maintains a Tic-Tac-Toe game for two client applications. 3 4 Imports System.Windows.Forms 5 Imports System.Net.Sockets 6 Imports System.Threading 7 8 Public Class FrmServer 9 Inherits Form 10 11 ' TextBox for displaying results 12 Friend WithEvents txtDisplay As TextBox 13 14 Private board As Char() ' Tic-Tac-Toe game board 15 16 Private players As CPlayer() ' player-client applications 17 Private playerThreads As Thread() ' Threads that run clients 18 19 ' indicates current player ("X" or "O") 20 Private currentPlayer As Integer 21 22 ' indicates whether server has disconnected 23 Private disconnect As Boolean = False 24 25 Public Sub New() 26 MyBase.New() 27 28 ' required by the Windows Form Designer 29 InitializeComponent() 30 31 ' add any initialization after the 32 ' InitializeComponent call 33 34 board = New Char(8) {} ' create board with nine squares 35 Creates a Char array to store the moves players made

28  2002 Prentice Hall. All rights reserved. Outline 28 Server.vb 36 players = New CPlayer(1) {} ' create two players 37 38 ' create one thread for each player 39 playerThreads = New Thread(1) {} 40 currentPlayer = 0 41 42 ' use separate thread to accept connections 43 Dim getPlayers As Thread = New Thread(New ThreadStart( _ 44 AddressOf SetUp)) 45 46 getPlayers.Start() 47 End Sub ' New 48 49 ' Visual Studio.NET generated code 50 51 ' invoked when user closes server window 52 Private Sub FrmServer_Closing(ByVal sender As System.Object, _ 53 ByVal e As System.ComponentModel.CancelEventArgs) _ 54 Handles MyBase.Closing 55 56 disconnect = True 57 End Sub ' FrmServer_Closing 58 59 ' accept connections from two client applications 60 Public Sub SetUp() 61 62 ' server listens for requests on port 5000 63 Dim listener As TcpListener = New TcpListener(5000) 64 listener.Start() 65 66 ' accept first client (player) and start its thread 67 players(0) = New CPlayer(listener.AcceptSocket(), Me, "X"c) 68 playerThreads(0) = _ 69 New Thread(New ThreadStart(AddressOf players(0).Run)) 70 Creates an array of two references to CPlayer objects Creates an array of two references to Thread objects Creates and starts Thread getPlayers which |the FrmServer uses to accept connections so that current Thread does not block while awaiting players Thread getPlayers executes method Setup Creates a TcpListener object to listen for requests on port 5000

29  2002 Prentice Hall. All rights reserved. Outline 29 Server.vb 71 playerThreads(0).Start() 72 73 ' accept second client (player) and start its thread 74 players(1) = New CPlayer(listener.AcceptSocket, Me, "O"c) 75 playerThreads(1) = _ 76 New Thread(New ThreadStart(AddressOf players(1).Run)) 77 78 playerThreads(1).Start() 79 80 ' inform first player of other player’s connection to server 81 SyncLock (players(0)) 82 83 players(0).threadSuspended = False 84 Monitor.Pulse(players(0)) 85 End SyncLock 86 87 End Sub ' SetUp 88 89 ' display message argument in txtDisplay 90 Public Sub Display(ByVal message As String) 91 txtDisplay.Text &= message & vbCrLf 92 End Sub ' Display 93 94 ' determine whether move is valid 95 Public Function ValidMove(ByVal location As Integer, _ 96 ByVal player As Char) As Boolean 97 98 ' prevent other threads from making moves 99 SyncLock(Me) 100 101 Dim playerNumber As Integer = 0 102 Create two Threads that execute and Run methods of each CPlayer object Sets the CPlayer’s threadSuspended variable to False Sends message to client indicating whether the move was valid

30  2002 Prentice Hall. All rights reserved. Outline 30 Server.vb 103 ' playerNumber = 0 if player = "X", else playerNumber = 1 104 If player = "O"c 105 playerNumber = 1 106 End If 107 108 ' wait while not current player's turn 109 While playerNumber <> currentPlayer 110 Monitor.Wait(Me) 111 End While 112 113 ' determine whether desired square is occupied 114 If Not IsOccupied(location) Then 115 116 ' place either an "X" or an "O" on board 117 If currentPlayer = 0 Then 118 board(location) = "X"c 119 Else 120 board(location) = "O"c 121 End If 122 123 ' set currentPlayer as other player (change turns) 124 currentPlayer = (currentPlayer + 1) Mod 2 125 126 ' notify other player of move 127 players(currentPlayer).OtherPlayerMoved(location) 128 129 ' alert other player to move 130 Monitor.Pulse(Me) 131 132 Return True 133 Else 134 Return False 135 End If 136 137 End SyncLock Invokes the Pulse method so the waiting CPlayer can validate a move

31  2002 Prentice Hall. All rights reserved. Outline 31 Server.vb 138 139 End Function ' ValidMove 140 141 ' determine whether specified square is occupied 142 Public Function IsOccupied(ByVal location As Integer) _ 143 As Boolean 144 145 ' return True if board location contains "X" or "O" 146 If (board(location) = "X"c OrElse _ 147 board(location) = "O"c) Then 148 149 Return True 150 Else 151 Return False 152 End If 153 154 End Function ' IsOccupied 155 156 ' allow clients to see if server has disconnected 157 Public ReadOnly Property Disconnected() As Boolean 158 159 Get 160 Return disconnect 161 End Get 162 163 End Property ' Disconnected 164 165 ' determine whether game is over 166 Public Function GameOver() As Boolean 167 168 ' place code here to test for winner of game 169 Return False 170 End Function ' GameOver 171 172 End Class ' FrmServer

32  2002 Prentice Hall. All rights reserved. Outline 32 Player.vb 1 ' Fig. 22.6: Player.vb 2 ' Represents a Tic-Tac-Toe player. 3 4 Imports System.Threading 5 Imports System.Net.Sockets 6 Imports System.IO 7 8 Public Class CPlayer 9 10 Private connection As Socket ' connection to server 11 Private server As FrmServer ' reference to Tic-Tac-Toe server 12 13 ' object for sending data to server 14 Private socketStream As NetworkStream 15 16 ' objects for writing and reading bytes to streams 17 Private writer As BinaryWriter 18 Private reader As BinaryReader 19 20 Private mark As Char ' "X" or "O" 21 Friend threadSuspended As Boolean = True 22 23 Sub New(ByVal socketValue As Socket, _ 24 ByVal serverValue As FrmServer, ByVal markValue As Char) 25 26 ' assign argument values to class-member values 27 connection = socketValue 28 server = serverValue 29 mark = markValue 30 31 ' use Socket to create NetworkStream object 32 socketStream = New NetworkStream(connection) 33 CPlayer constructor takes Socket object, FrmServer object and Char as three arguments

33  2002 Prentice Hall. All rights reserved. Outline 33 Player.vb 34 ' create objects for writing and reading bytes across streams 35 writer = New BinaryWriter(socketStream) 36 reader = New BinaryReader(socketStream) 37 End Sub ' New 38 39 ' inform other player that move was made 40 Public Sub OtherPlayerMoved(ByVal location As Integer) 41 42 ' notify opponent 43 writer.Write("Opponent moved") 44 writer.Write(location) 45 End Sub ' OtherPlayerMoved 46 47 ' inform server of move and receive move from other player 48 Public Sub Run() 49 50 Dim done As Boolean = False ' indicates whether game is over 51 52 ' indicate successful connection and send mark to server 53 If mark = "X"c Then 54 server.Display("Player X connected") 55 writer.Write(mark) 56 writer.Write("Player X connected" & vbCrLf) 57 Else 58 server.Display("Player O connected") 59 writer.Write(mark) 60 writer.Write("Player O connected, please wait" & vbCrLf) 61 End If 62 63 ' wait for other player to connect 64 If mark = "X"c Then 65 writer.Write("Waiting for another player") 66 FrmServer calls method RunNotify the server of successful connection

34  2002 Prentice Hall. All rights reserved. Outline 34 Player.vb 67 ' wait for notification that other player has connected 68 SyncLock (Me) 69 70 While ThreadSuspended 71 Monitor.Wait(Me) 72 End While 73 74 End SyncLock 75 76 writer.Write("Other player connected. Your move") 77 End If 78 79 ' play game 80 While Not done 81 82 ' wait for data to become available 83 While connection.Available = 0 84 Thread.Sleep(1000) 85 86 ' end loop if server disconnects 87 If server.Disconnected Then 88 Return 89 End If 90 91 End While 92 93 ' receive other player's move 94 Dim location As Integer = reader.ReadInt32() 95 96 ' determine whether move is valid 97 If server.ValidMove(location, mark) Then 98 99 ' display move on server 100 server.Display("loc: " & location) 101 Defines the While loop that suspends CPlayer “X” Thread until the server signals that CPlayer “O” has connected Executes the While structure enabling the user to play the game Property Disconnected checks whether server variable disconnect is True Calls method ReadInt32 of the BinaryReader object Passes the integer to server method ValidMove

35  2002 Prentice Hall. All rights reserved. Outline 35 Player.vb 102 ' notify server of valid move 103 writer.Write("Valid move.") 104 105 Else ' notify server of invalid move 106 writer.Write("Invalid move, try again") 107 End If 108 109 ' exit loop if game over 110 If server.GameOver Then 111 done = True 112 End If 113 114 End While 115 116 ' close all connections 117 writer.Close() 118 reader.Close() 119 socketStream.Close() 120 connection.Close() 121 End Sub ' Run 122 123 End Class ' CPlayer

36  2002 Prentice Hall. All rights reserved. Outline 36 Client.vb 1 ' Fig. 22.7: Client.vb 2 ' Client for the Tic-Tac-Toe program. 3 4 Imports System.Windows.Forms 5 Imports System.Net.Sockets 6 Imports System.Threading 7 Imports System.IO 8 9 Public Class FrmClient 10 Inherits Form 11 12 ' board contains nine panels where user can place "X" or "O" 13 Friend WithEvents Panel1 As Panel 14 Friend WithEvents Panel2 As Panel 15 Friend WithEvents Panel3 As Panel 16 Friend WithEvents Panel4 As Panel 17 Friend WithEvents Panel5 As Panel 18 Friend WithEvents Panel6 As Panel 19 Friend WithEvents Panel7 As Panel 20 Friend WithEvents Panel8 As Panel 21 Friend WithEvents Panel9 As Panel 22 23 ' TextBox displays game status and other player's moves 24 Friend WithEvents txtDisplay As TextBox 25 Friend WithEvents lblId As Label ' Label displays player 26 27 Private board As CSquare(,) ' Tic-Tac-Toe board 28 29 ' square that user previously clicked 30 Private mCurrentSquare As CSquare 31 32 Private connection As TcpClient ' connection to server 33 Private stream As NetworkStream ' stream to tranfser data 34

37  2002 Prentice Hall. All rights reserved. Outline 37 Client.vb 35 ' objects for writing and reader bytes to streams 36 Private writer As BinaryWriter 37 Private reader As BinaryReader 38 39 Private mark As Char ' "X" or "O" 40 Private turn As Boolean ' indicates which player should move 41 42 Private brush As SolidBrush ' brush for painting board 43 44 Private done As Boolean = False ' indicates whether game is over 45 46 Public Sub New() 47 MyBase.New() 48 49 ' required by the Windows Form Designer 50 InitializeComponent() 51 52 ' add any initialization after the 53 ' InitializeComponent call 54 55 board = New CSquare(2, 2) {} ' create 3 x 3 board 56 57 ' create nine CSquare's and place their Panels on board 58 board(0, 0) = New CSquare(Panel1, " "c, 0) 59 board(0, 1) = New CSquare(Panel2, " "c, 1) 60 board(0, 2) = New CSquare(Panel3, " "c, 2) 61 board(1, 0) = New CSquare(Panel4, " "c, 3) 62 board(1, 1) = New CSquare(Panel5, " "c, 4) 63 board(1, 2) = New CSquare(Panel6, " "c, 5) 64 board(2, 0) = New CSquare(Panel7, " "c, 6) 65 board(2, 1) = New CSquare(Panel8, " "c, 7) 66 board(2, 2) = New CSquare(Panel9, " "c, 8) 67 68 ' create SolidBrush for writing on Squares 69 brush = New SolidBrush(Color.Black) The FrmClient’s constructor

38  2002 Prentice Hall. All rights reserved. Outline 38 Client.vb 70 71 ' make connection request to server at port 5000 72 connection = New TcpClient("localhost", 5000) 73 stream = connection.GetStream() 74 75 ' create objects for writing and reading bytes to streams 76 writer = New BinaryWriter(stream) 77 reader = New BinaryReader(stream) 78 79 ' create thread for sending and receiving messages 80 Dim outputThread As Thread = New Thread(AddressOf Run) 81 outputThread.Start() 82 End Sub ' New 83 84 ' Visual Studio.NET generated code 85 86 ' invoked on screen redraw 87 Private Sub FrmClient_Paint(ByVal sender As System.Object, _ 88 ByVal e As System.Windows.Forms.PaintEventArgs) _ 89 Handles MyBase.Paint 90 91 PaintSquares() 92 End Sub 93 94 ' invoked when user closes client application 95 Private Sub FrmClient_Closing(ByVal sender As System.Object, _ 96 ByVal e As System.ComponentModel.CancelEventArgs) _ 97 Handles MyBase.Closing 98 99 done = True 100 End Sub 101 102 ' redraw Tic-Tac-Toe board 103 Public Sub PaintSquares() 104 Dim graphics As Graphics Opens a connection to the server and obtains a reference to the connection associated NetworkStream object from TcpClient

39  2002 Prentice Hall. All rights reserved. Outline 39 Client.vb 105 106 ' counters for traversing Tic-Tac-Toe board 107 Dim row As Integer 108 Dim column As Integer 109 110 ' draw appropriate mark on each panel 111 For row = 0 To 2 112 113 For column = 0 To 2 114 115 ' get Graphics for each Panel 116 graphics = board(row, column).Panel.CreateGraphics() 117 118 ' draw appropriate letter on panel 119 graphics.DrawString(board(row, _ 120 column).Mark.ToString(), Me.Font, brush, 8, 8) 121 Next 122 Next 123 124 End Sub ' PaintSquares 125 126 ' invoked when user clicks Panels 127 Private Sub square_MouseUp(ByVal sender As System.Object, _ 128 ByVal e As System.Windows.Forms.MouseEventArgs) Handles _ 129 Panel1.MouseUp, Panel2.MouseUp, Panel3.MouseUp, _ 130 Panel4.MouseUp, Panel5.MouseUp, Panel6.MouseUp, _ 131 Panel7.MouseUp, Panel8.MouseUp, Panel9.MouseUp 132 133 ' counters for traversing Tic-Tac-Toe board 134 Dim row As Integer 135 Dim column As Integer 136 137 For row = 0 To 2 138

40  2002 Prentice Hall. All rights reserved. Outline 40 Client.vb 139 For column = 0 To 2 140 141 ' determine which Panel was clicked 142 If board(row, column).Panel Is sender Then 143 mCurrentSquare = board(row, column) 144 145 ' send move to server 146 SendClickedSquare(board(row, column).Location) 147 End If 148 149 Next 150 Next 151 152 End Sub ' square_MouseUp 153 154 ' continuously update TextBox display 155 Public Sub Run() 156 157 Dim quote As Char = ChrW(34) ' single quote 158 159 ' get player's mark ("X" or "O") 160 mark = Convert.ToChar(stream.ReadByte()) 161 lblId.Text = "You are player " & quote & mark & quote 162 163 ' determine which player's should move 164 If mark = "X" Then 165 turn = True 166 Else 167 turn = False 168 End If 169 170 ' process incoming messages 171 Try 172

41  2002 Prentice Hall. All rights reserved. Outline 41 Client.vb 173 ' receive messages sent to client 174 While True 175 ProcessMessage(reader.ReadString()) 176 End While 177 178 ' notify user if server closes connection 179 Catch exception As EndOfStreamException 180 txtDisplay.Text = "Server closed connection. Game over." 181 182 End Try 183 184 End Sub ' Run 185 186 ' process messages sent to client 187 Public Sub ProcessMessage(ByVal messageValue As String) 188 189 ' if valid move, set mark to clicked square 190 If messageValue = "Valid move." Then 191 txtDisplay.Text &= "Valid move, please wait." & vbCrLf 192 mCurrentSquare.Mark = mark 193 PaintSquares() 194 195 ' if invalid move, inform user to try again 196 ElseIf messageValue = "Invalid move, try again" Then 197 txtDisplay.Text &= messageValue & vbCrLf 198 turn = True 199 200 ' if opponent moved, mark opposite mark on square 201 ElseIf messageValue = "Opponent moved" Then 202 203 ' find location of opponent's move 204 Dim location As Integer = reader.ReadInt32() 205 Indicates if the move is validIndicates if the move is invalid Indicates if the opponent made a move Reads form the server an Integer specifying where on the board the client should place the opponent’s mark

42  2002 Prentice Hall. All rights reserved. Outline 42 Client.vb 206 ' mark that square with opponent's mark 207 If mark = "X" Then 208 board(location \ 3, location Mod 3).Mark = "O"c 209 Else 210 board(location \ 3, location Mod 3).Mark = "X"c 211 End If 212 213 PaintSquares() 214 215 txtDisplay.Text &= "Opponent moved. Your turn." & vbCrLf 216 217 turn = True ' change turns 218 219 ' display message as default case 220 Else 221 txtDisplay.Text &= messageValue & vbCrLf 222 End If 223 224 End Sub ' ProcessMessage 225 226 ' send square position to server 227 Public Sub SendClickedSquare(ByVal location As Integer) 228 229 ' send location to the server if current turn 230 If turn Then 231 writer.Write(location) 232 turn = False ' change turns 233 End If 234 235 End Sub ' SendClickedSquare 236 237 ' Property CurrentSquare 238 Public WriteOnly Property CurrentSquare() As CSquare 239

43  2002 Prentice Hall. All rights reserved. Outline 43 Client.vb 240 Set(ByVal Value As CSquare) 241 mCurrentSquare = Value 242 End Set 243 244 End Property ' CurrentSquare 245 246 End Class ' FrmClient

44  2002 Prentice Hall. All rights reserved. Outline 44 Client.vb

45  2002 Prentice Hall. All rights reserved. Outline 45 Client.vb

46  2002 Prentice Hall. All rights reserved. Outline 46 Square.vb 1 ' Fig. 22.8: Square.vb 2 ' Represents a square on the Tic-Tac-Toe board. 3 4 Public Class CSquare 5 6 Private squarePanel As Panel ' panel on which user clicks 7 Private squareMark As Char ' "X" or "O" 8 Private squareLocation As Integer ' position on board 9 10 ' constructor assigns argument values to class-member values 11 Public Sub New(ByVal panelValue As Panel, _ 12 ByVal markValue As Char, ByVal locationValue As Integer) 13 14 squarePanel = panelValue 15 squareMark = markValue 16 squareLocation = locationValue 17 End Sub ' New 18 19 ' return panel on which user can click 20 Public ReadOnly Property Panel() As Panel 21 22 Get 23 Return squarePanel 24 End Get 25 26 End Property ' Panel 27 28 ' set and get squareMark ("X" or "O") 29 Public Property Mark() As Char 30 31 Get 32 Return squareMark 33 End Get 34

47  2002 Prentice Hall. All rights reserved. Outline 47 Square.vb 35 Set(ByVal Value As Char) 36 squareMark = Value 37 End Set 38 39 End Property ' Mark 40 41 ' return squarePanel position on Tic-Tac-Toe board 42 Public ReadOnly Property Location() As Integer 43 44 Get 45 Return squareLocation 46 End Get 47 48 End Property ' Location 49 50 End Class ' CSquare


Download ppt " 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a."

Similar presentations


Ads by Google