public class Server { public static void main(String[] args)throws IOException { int port = 8033; ServerSocket server = new ServerSocket(port);
while (true) { Socket sock = server.accept(); InputStreamReader in = new InputStreamReader(sock.getInputStream()); StringBuffer sb = new StringBuffer(8096);
System.out.println("Handling client at " + sock.getRemoteSocketAddress()); boolean bRet = true; while (bRet) { if (in.ready()) { int idx = 0; while (idx != -1) { idx = in.read(); sb.append((char)idx); } }else { bRet = false; } } in.close(); // 为什么交换前后两句的顺序,会出现不同的效果? System.out.println(sb.toString());
} } }
import java.io.*; import java.net.*;
public class Client { public static void main(String[] args) { byte[] data = "just try".getBytes(); try { Socket sock = new Socket("127.0.0.1", 8033); OutputStream out = sock.getOutputStream(); out.write(data); sock.close(); } catch (IOException e) { e.printStackTrace(); } } }
[解决办法] 为什么没人回复啊```
我在想是不是因为client中没有: out.flush(); out.close();
试过之后还是不行... HELP HELP HELP 到底是服务端有问题还是客戶端??? 怎么看起来这么简单的问题,没人会呢?? [解决办法] 首先,第一个 // 为什么交换前后两句的顺序,会出现不同的效果? 你关闭流的时候,是先关闭 StringBuffer,然后再关闭InputStreamReader,你那个语句等于关闭了InputStreamReader再使用StringBuffer。 [解决办法] 启动Server后,一次次执行Client。“Just try”消息,有时可以接收到,有时不能。这是为什么啊?谁能告诉我··· 我觉得是缓冲区问题,我想知道具体原因。先谢过了!!! 这个问题你既然可以接收到,就证明你程序是没有问题的。 我猜最大的原因就是你操作的问题,关闭的时候一定要关闭服务端和客户端,否则下一次使用的时候就有可能出错。 另外out.flush();是必须的。 [解决办法] 在server端,有可能是接受不到数据的,因为最后弄一个end字符串表示结束比较好,在客户端也是的。 [解决办法]
public int read() throws IOException Reads a single character. Overrides: read in class Reader Returns:The character read, or -1 if the end of the stream has been reached Throws: IOException - If an I/O error occurs [解决办法]
好像是... 这是为什么?帮忙分析分析~ [解决办法] 对于 InputStreamReader.ready() 函数 Note that returning false does not guarantee that the next read will block.
Yes!!!问题就是出在这里,是我们没弄清楚这个ready()方法 public boolean ready() throws IOException Tells whether this stream is ready to be read. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream. 谁能解释下这个红字的意思?就应该是它没理解清楚。。。 [解决办法]