私はホームサーバーで実行するJavaプログラムを持っています。私はまた、サーバーにメッセージを送信し、ソケットを使用して応答を受け取るJavaクライアントプログラムを持っています。Javaソケット通信 - 速度の向上
私はそれをうまく実装しましたが、少し遅くなり、できるだけ早くそれを取得しようとしています。ここで
は私のコードです:
サーバー
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) {
}
クライアント
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
}
}
したがって、たとえば、私はどのようにサーバーを決定するために、サーバに様々な文字列を送信します応答します。たとえば、コードに見られるように、サーバーに「marco」を送信すると、「polo」が返されます。私はまた、メッセージが終わったことをプログラムに知らせるための区切り文字として(char) 13
を持っています。
誰かが転送の時間を短縮する方法についていくつか考えていますか?私は、ナグルのアルゴリズムを無効にするなどのことを読んだ。助けてくれますか?おそらくソケットは私が純粋なスピードを望むならば行く方法ではありません。たぶん異なる言語やライブラリが速くなるでしょうか?
あなたは「少し遅い」と思いますか? – Mat
できるだけ早くそれを必要とするケースが増えています:) –
はい、それは私の主張です。それはどういうことなのですか? – Mat