Something went wrong on our end
-
Brutzman, Don authoredBrutzman, Don authored
YamashitaDeMouraTcpServer.java 2.74 KiB
import java.io.*;
import java.net.*;
/**
* MV3500
*
* TCP Server.
* This server works with only one client and can exchange
* multiples messages with it.
*
* @author Douglas Yamashita de Moura
* @version 20180212
*
*/
public class YamashitaDeMouraTcpServer
{
public static void main(String[] args)
{
try
{
ServerSocket serverSocket = new ServerSocket(2317);
System.out.print("Server socket created. Waiting for client...\n");
Socket clientConnection = serverSocket.accept();
InetAddress localAddress = clientConnection.getLocalAddress();
InetAddress remoteAddress = clientConnection.getInetAddress();
int localPort = clientConnection.getLocalPort();
int remotePort = clientConnection.getPort();
System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " +
remoteAddress.toString() + ", " + remotePort + " ))\n");
int count = 1;
boolean openConnection = true;
while(openConnection)
{
String response = "";
System.out.println("Request #" + count);
// Receives message from client
InputStream is = clientConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientMessage = br.readLine();
System.out.println("The message the client sent was: " + clientMessage + ".");
// Sends message to client
OutputStream os = clientConnection.getOutputStream();
PrintStream ps = new PrintStream(os);
switch (count){
case 1:
response = "'I am the server and I accepted the request. Send entity name and position.'\n";
break;
case 2:
response = "'I confirm the receipt of the message.'\n";
break;
case 3:
response = "'You are welcome. Closing connection.'\n";
openConnection = false;
break;
}
System.out.println("Message sent to client: " + response);
ps.print(response);
ps.flush();
response = "";
count++;
}
clientConnection.close();
} catch(Exception e){
System.out.println("Problem with networking");
System.out.println("Exception: " + e);
}
}
}