I have developed this simple TCP Server/Client communication program, and am looking for ways of lowering the code footprint where possible.Side note, Both Classes are Main as they run independently, though interact.
TCPClient
package socketUse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;
class TCPClient
{
public static void main(String[] args) throws Exception
{
try
{
String input;
String modedInput;
System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
@SuppressWarnings("resource")
Socket client = new Socket("localhost", 22003);
client.setSoTimeout(3000);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
input = inFromUser.readLine();
outToServer.writeBytes(input + '\n');
modedInput = inFromServer.readLine();
System.out.println("You Sent: " + modedInput);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
catch(SocketTimeoutException e)
{
System.out.println("Timed Out Waiting for a Response from the Server");
}
}
}
TCPServer
package socketUse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
class TCPServer
{
public static void main(String[] args) throws Exception
{
try
{
String TCPclientMess;
String returnMess;
@SuppressWarnings("resource")
ServerSocket input = new ServerSocket(22003);
while(true)
{
Socket connectionSocket = input.accept();
BufferedReader iptFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream optToClient = new DataOutputStream(connectionSocket.getOutputStream());
TCPclientMess = iptFromClient.readLine();
System.out.println("You Sent: " + TCPclientMess);
returnMess = TCPclientMess;
optToClient.writeBytes(returnMess);
}
}
catch(Exception e)
{
e.getStackTrace();
}
}
}