Something went wrong on our end
-
Brutzman, Don authoredBrutzman, Don authored
MaroonTcpServer.java 2.78 KiB
package tcpserver;
import java.io.*;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
/**
* Very slightly more complex than example1. A complete copy of
* example 2. The only thing this does
* differently is introduce a loop into the response, so you don't
* have to restart the program after one response. Also, it prints
* out the socket pair the server sees. Run the program via telnet
* several times and compare the socket pairs.
*
* telnet localhost 2317
*
* If you're sophisticated you can contact the instructor's computer
* while running this program.
*
* telnet <ipOfServersLaptop> 2317
*
* And have him display the socket pairs he got.
* @author mcgredo
*/
public class MaroonTcpServer
{
public static DataInputStream input;
public static DataOutputStream output;
public static void main(String[] args)
{
MaroonUnit testUnit1 = new MaroonUnit ();
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();
//OutputStream os = clientConnection.getOutputStream();
input = new DataInputStream(clientConnection.getInputStream());
output = new DataOutputStream(clientConnection.getOutputStream());
String request = input.readUTF();
if ("position".equals(request)){
output.writeUTF(Arrays.toString(testUnit1.getPosition()));
}
else if ("ID".equals(request)){
output.writeUTF(""+ testUnit1.getID());
}else
output.writeUTF("I don't understand, try www.google.com");
// 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.
clientConnection.close();
}
}
catch(Exception e)
{
System.out.println("problem with networking");
}
}
}