我有一個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
作爲分隔符讓程序知道消息已結束。
有沒有人有關於如何降低轉移時間的一些想法?我讀過關於禁用nagle算法等事情。這會有幫助嗎?如果我想純粹的速度,也許套接字不是要走的路。也許不同的語言或圖書館會更快?
是什麼讓你覺得它「有點慢」? – Mat
更多的情況下,我需要儘可能快:) –
是的,這是我的觀點:你怎麼知道它不是? – Mat