30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1106 Networking: Streams-Based Sockets and Datagrams Chapter 22<br />

71 ' handle exception if error occurs in sending data <strong>to</strong> server<br />

72 Catch exception As SocketException<br />

73 txtDisplay.Text &= vbCrLf & "Error writing object"<br />

74 End Try<br />

75<br />

76 End Sub ' txtInput_KeyDown<br />

77<br />

78 ' connect <strong>to</strong> server and display server-generated text<br />

79 Public Sub RunClient()<br />

80 Dim client As TcpClient<br />

81<br />

82 ' instantiate TcpClient for sending data <strong>to</strong> server<br />

83 Try<br />

84<br />

85 txtDisplay.Text &= "Attempting connection" & vbCrLf<br />

86<br />

87 ' Step 1: create TcpClient and connect <strong>to</strong> server<br />

88 client = New TcpClient()<br />

89 client.Connect("localhost", 5000)<br />

90<br />

91 ' Step 2: get NetworkStream associated with TcpClient<br />

92 output = client.GetStream()<br />

93<br />

94 ' create objects for writing and reading across stream<br />

95 writer = New BinaryWriter(output)<br />

96 reader = New BinaryReader(output)<br />

97<br />

98 txtDisplay.Text &= vbCrLf & "Got I/O streams" & vbCrLf<br />

99<br />

100 txtInput.ReadOnly = False<br />

101<br />

102 ' Step 3: processing phase<br />

103 Try<br />

104<br />

105 ' loop until server signals termination<br />

106 Do<br />

107<br />

108 ' read message from server<br />

109 message = reader.ReadString<br />

110 txtDisplay.Text &= vbCrLf & message<br />

111<br />

112 Loop While message "SERVER>>> TERMINATE"<br />

113<br />

114 ' handle exception if error in reading server data<br />

115 Catch inputOutputException As IOException<br />

116 MessageBox.Show("Client application closing")<br />

117<br />

118 ' Step 4: close connection<br />

119 Finally<br />

120<br />

121 txtDisplay.Text &= vbCrLf & "Closing connection." & _<br />

122 vbCrLf<br />

123<br />

Fig. 22.2 Client portion of a client/server stream-socket connection (part 3 of 5).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!