问题
要做成这样的:
客户端访问服务器ip和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()即可发送啊,搞不懂搞不懂,这样我的握手协议怎么做啊??
关于java socket的问题
80酷酷网 80kuku.com