關於java socket的問題
來源:互聯網
上載者:User
問題
要做成這樣的:
Client Access Serverip和port,伺服器馬上發送welcome訊息,然後用戶端根據welcome訊息判斷是否是想要已連線的服務器和連接埠,
如果是則開始發送資料,資料包括開始和結束的校正。伺服器端發送welcome訊息後開始接收資料,直到結束。蠻簡單的事TMD我怎麼就搞不定。
CLIENT:
package com.ces.mytest.socket;
import java.net.*;import java.io.*;
public class ClientThread extends Thread { private String ipStr = ""; private int port; public ClientThread(String ipStr, int port) { this.ipStr = ipStr; this.port = port; }
public void run() { try { Socket client = new Socket(ipStr, port); BufferedReader read = new BufferedReader(new InputStreamReader(client.getInputStream())); BufferedWriter write = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
if ("歡迎".equals(read.readLine())) { System.out.println("校正正確");
write.write("開始"); write.newLine(); write.write("資料"); write.newLine(); write.write("結束"); write.newLine(); write.flush();
System.out.println("發送完畢"); }
write.close(); read.close(); client.close(); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
public static void main(String[] args) { Thread client = new ClientThread("127.0.0.1",10020); client.start(); }
}
SERVER:
package com.ces.mytest.socket;
import java.net.*;import java.io.*;
public class ServerThread extends Thread { private int port; public ServerThread(int port) { this.port = port; }
private boolean stop = false;
public void run() { try { ServerSocket server = new ServerSocket(port); while (!stop) { Socket client = server.accept(); BufferedReader read = new BufferedReader(new InputStreamReader(client.getInputStream())); BufferedWriter write = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); System.out.println("發送歡迎資訊"); write.write("歡迎"); write.flush();
// String lineStr = read.readLine();// if ("開始".equals(lineStr)) {// System.out.println("開始接受資料!");//// while (true) {// lineStr = read.readLine();// if ("結束".equals(lineStr)) {// break;// } else {// System.out.println("資料是" + lineStr);// }// }// }
write.close(); read.close(); client.close(); }
} catch (IOException ex) { ex.printStackTrace(); } }
public static void main(String[] args) { Thread server = new ServerThread(10020); server.start(); }
public boolean isStop() { return stop; }
public void setStop(boolean stop) { this.stop = stop; }}
只要我將ServerThread類的String lineStr = read.readLine();的注釋去掉,程式肯定出問題,什麼問題呢?分析發現ServerThread的Output流必須等write.close()執行完才發送,而read.readLine()程式就會停在那裡,所謂的block程式,可參考上明明說write.flush()即可發送啊,搞不懂搞不懂,這樣我的握手協議怎麼做啊??