/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package mv3500code; 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 BlankenbekerMyTcpClient { 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); // 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 serverMessage = br.readLine(); System.out.println("The message the server sent was " + serverMessage); OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); ps.println("This response was written by myTcpClient"); // to remote client // "flush()" in important in that it forces a write // across what is in fact a slow connection ps.flush(); } } catch(IOException e) { System.out.println(e); System.out.println("Problem with client :" + e); } System.out.println("client exit"); } }