//package tcpclient; import java.net.Socket; import java.io.*; import java.net.*; /** * Before, we always used telnet to connect to the server. We are now writing * our own program to do the connection. * * As you will see, when we run this after we start the server we will see the * same string telnet printed, sent by the server. The output at the server will * show different socket pairs for each time we ran it. * * @author mcgredo */ public class TackettTcpClient { public final static String LOCALHOST = "localhost"; //String can also be IPV4 127.0.0.1 or IPV6 0:0:0:0:0:0:0:1 public static void main(String[] args) { try { //while (true) { System.out.println("creating socket"); // We request an IP to connect to ("localhost") and // port number at that IP (2317). This establishes // a connection to that IP in the form of the Socket // object; the server uses a ServerSocket to wait for // connections. Socket socket = new Socket(LOCALHOST, 2317); OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); String locationMessage = "Enemy infantry spotted in the open at position Alpha"; String sendMessage = locationMessage + "\n"; bw.write(sendMessage); bw.flush(); System.out.println("Message sent to the server: " + sendMessage); // Read the single line written by the server. We'd // do things a bit differently if many lines to be read // from the server, instead of one only. InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String message = br.readLine(); System.out.println("Message received from the server: "+message); String serverMessage = br.readLine(); System.out.println("Now we're talking"); System.out.println("The message the server sent was " + serverMessage); } catch(Exception exception) { // System.out.println(e); exception.printStackTrace(); System.out.println("Problem with client"); System.out.println(exception); } finally { try { //socket.close(); } catch(Exception e) { e.printStackTrace(); } } System.out.println("client exit"); } }