Something went wrong on our end
DemchkoServer.java 3.07 KiB
package MV3500Cohort2018JulySeptember.homework2.Demchko;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author ekdem
*/
public class DemchkoServer {
@SuppressWarnings("ConvertToTryWithResources")
/**
* Program invocation, execution starts here
* @param args command-line arguments
*/
public static void main(String[] args)
{
try {
// ServerSocket waits for a connection from a client.
// Notice that it is outside the loop; ServerSocket
// needs to be made only once.
ServerSocket serverSocket = new ServerSocket(2317);
// Loop, infinitely, waiting for client connections.
// Stop the program somewhere else.
while (true)
{
Socket clientConnection = serverSocket.accept(); // block until connected
OutputStream os = clientConnection.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner keyboard = new Scanner(System.in);
System.out.println("Why did the chicken cross the road?");
String message = keyboard.nextLine();
ps.println(message);
// Print some information locally about the Socket
// connection. This includes the port and IP numbers
// on both sides (the socket pair.)
InetAddress localAddress = clientConnection.getLocalAddress();
InetAddress remoteAddress = clientConnection.getInetAddress();
int localPort = clientConnection.getLocalPort();
int remotePort = clientConnection.getPort();
// My socket pair connection looks like this, to localhost:
// Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 ))
// Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 ))
//
// Why is the first IP/port the same, while the second set has
// different ports?
System.out.println("Socket pair: (( " + localAddress.toString().trim() + ", " + localPort + " ), ( "
+ remoteAddress.toString() + ", " + remotePort + " ))");
InputStream is = clientConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String serverMessage = br.readLine();
System.out.println("This time try " + serverMessage);
// Notice the use of flush() and close(). Without
// the close() to Socket object may stay open for
// a while after the client has stopped needing this
// connection. Close() explicitly ends the connection.
ps.flush();
clientConnection.close(); // like it or not, you're outta here!
}
}
catch (IOException e) {
System.out.println("Houston, we have a problem: " + e);
}
}
}