Java Reference
In-Depth Information
2. Communicate using the socket's I/O streams: A connected instance of Socket contains
an InputStream and OutputStream that can be used just like any other Java I/O stream (see
Chapter 3).
3. Close the connection using the close() method of Socket .
Our first TCP application, called TCPEchoClient.java , is a client that communicates with an
echo server using TCP. An echo server simply repeats whatever it receives back to the client.
The string to be echoed is provided as a command-line argument to our client. Many systems
include an echo server for debugging and testing purposes. To test if the standard echo server
is running, try telnetting to port 7 (the default echo port) on the server (e.g., at command line
telnet server.example.com 7” or use your basic telnet application).
TCPEchoClient.java
0 import java.net.*; // for Socket
1 import java.io.*;
// for IOException and Input/OutputStream
2
3 public class TCPEchoClient {
4
5
public static void main(String[] args) throws IOException {
6
7
if ((args.length < 2) || (args.length > 3)) // Test for correct # of args
8
throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");
9
10
String server = args[0];
// Server name or IP address
11
// Convert input String to bytes using the default character encoding
12
byte[] byteBuffer = args[1].getBytes();
13
14
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
15
16
// Create socket that is connected to server on specified port
17
Socket socket = new Socket(server, servPort);
18
System.out.println("Connected to server...sending echo string");
19
20
InputStream in = socket.getInputStream();
21
OutputStream out = socket.getOutputStream();
22
23
out.write(byteBuffer); // Send the encoded string to the server
24
25
// Receive the same string back from the server
26
int totalBytesRcvd = 0; // Total bytes received so far
27
int bytesRcvd;
// Bytes received in last read
28
while (totalBytesRcvd < byteBuffer.length) {
29
if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd,
30
byteBuffer.length − totalBytesRcvd)) == −1)
31
throw new SocketException("Connection closed prematurely");
 
Search WWH ::




Custom Search