Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- /*
- This is the client side of the TCP client/server example
- */
- public class FSC {
- public static void main (String args[])throws Exception{
- /* if you have time at the end take a look at the exceptions that might be raised and think about nicer ways of handling them */
- String reply;
- // prepare to get input from the console
- // A BufferedReader provides nice methods like readLine()
- // and is more efficient than just using InputStreamReader
- BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
- // create the client socket
- // This is just a generic Socket object - we need to specify
- // the address (or name) of machine running your server,
- // plus the port number your server is listening on
- // if this method doesn't throw an exception, then we have
- // successfully opened a connection to the server
- // If you get an error like "connection refused", then the
- // server probably isn't running
- Socket clientSocket = new Socket("localhost", 2845);
- //InetAddress host = clientSocket.getInetAddress();
- // BufferedReader gives us the readLine() method, and an
- // InputStreamReader decodes bytes into characters
- BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- // read the actual sentence from the console
- System.out.print("Password: ");
- String messageCmd = inFromUser.readLine();
- String messagePrm = inFromUser.readLine();
- // write a stream of bytes to the socket
- // we need the end-of-line character so the server knows when
- // the client has stopped sending (actually so the readLine()
- // method works)
- sendCommand(messageCmd, messagePrm);
- //outToServer.writeBytes(message + "\n");
- // get the response from the server - this method waits until
- // the server has sent a whole string
- reply = inFromServer.readLine();
- System.out.println(reply);
- // close the socket and the connection
- clientSocket.close();
- }
- public static String sendCommand(String messageCmd, String messagePrm){
- // a DataOutputStream is a portable way of feeding Java types
- // into something that expects a stream of bytes (a socket doesn't
- // know about strings/ints etc, it just sees bytes)
- // Java IO is ridiculously complicated ...
- DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
- outToServer.writeBytes(messageCmd + " " + messagePrm + "\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement