分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
来自于一个论坛帖子: http://topic.csdn.net/u/20081231/06/6a1e156c-3015-4e93-9bcc-19ee2b32b13b.html
我修改了代码,方便测试
1 Server.java 服务器端
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Server {
- /**
- * @param args
- * the command line arguments
- */
- public static void main(String[] args) throws IOException {
- String data = "Toobie ornaught toobie";
- try {
- ServerSocket srvr = new ServerSocket(8085);
- Socket skt = srvr.accept();
- System.out.print("Server has connected!/n");
- BufferedReader in = new BufferedReader(new InputStreamReader(skt
- .getInputStream()));
- PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
- System.out.print("Sending string: '" + data + "'/n");
- out.print(data); //############ 问题就出现在这里 ##################
- System.out.print("Sending string: '" + data + "'/n");
- while (!in.ready()) {
- }
- System.out.println(in.readLine());
- out.close();
- in.close();
- skt.close();
- srvr.close();
- } catch (Exception e) {
- System.out.print("Whoops! It didn't work!/n");
- }
- }
- }
2 Client.java 客户端
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class Client {
- /**
- * @param args
- * the command line arguments
- */
- public static void main(String[] args) throws IOException {
- try {
- Socket skt = new Socket("localhost", 8085);
- BufferedReader in = new BufferedReader(new InputStreamReader(skt
- .getInputStream()));
- PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
- String inputLine, outputLine;
- while (!in.ready()) {
- }
- System.out.println(in.readLine());
- out.print("aaa");
- out.close();
- in.close();
- skt.close();
- } catch (Exception e) {
- System.out.print("Whoops! It didn't work!/n");
- }
- }
- }
系统运行后,停止响应,都在等待。经检查,那个out.print是问题的根本。
换成
out.println(data);
即可:
原因是,使用readLine,而这个只有2个可能性会继续
1 遇到了换行符
2 遇到了数据结尾
而你只发送了
out.print(data);
对面根本不知道你已经发送完了数据, 所以继续等待你的换行呢。。。。
当然,如果你在客户端不用readline,而是用read读取字节,则不会出现这个问题了。这也是readLine的特殊性。