I have a java program which I run on a home server. I have also a java client program which sends messages to the server and receives a response using sockets.
I have implemented it successfully, but It seems a little slow and am trying to get it as fast as possible.
Here is my code:
Server
public class Server implements Runnable{
static ServerSocket socket1;
protected final static int port = 4701;
static Socket connection;
static StringBuffer process;
private String handleRequest(String req){
if(req.equals("marco")){
return "polo";
}else
return "null";
}
public void run(){
try {
socket1 = new ServerSocket(port);
int character;
while (true) {
connection = socket1.accept();
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
process = new StringBuffer();
while ((character = isr.read()) != 13) {
process.append((char) character);
}
String returnCode = handleRequest(process.toString()) + (char) 13;
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write(returnCode);
osw.flush();
}
} catch (IOException e) {
System.out.println("error starting server " + e.getMessage());
}
try {
if(connection != null)
connection.close();
} catch (IOException e) {
}
Client
String host = "xx.xx.xx.xxx";
int port = 4701;
StringBuffer instr = new StringBuffer();
try {
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.
getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
String process = "marco" + (char) 13;
osw.write(process);
osw.flush();
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
int c;
while ( (c = isr.read()) != 13)
instr.append( (char) c);
connection.close();
}
catch (Exception e){}
if(instr.toString().equals("")){
//error
}
}
So for example, I will send various strings to the server to determine how the server will response. So for example, as seen in the code, If I send "marco" to the server I get "polo" returned. I also have (char) 13 as a delimiter to let the program know the message is over.
Does anyone have some ideas on how to lower the time for the transfers? I've read about things such as disabling nagle's algorithm. Would that help? Perhaps sockets isn't the way to go if I want pure speed. Maybe a different language or library will be faster?