ITeye博客

关于socket编程的一个很有意思的问题

lengyimeng · 2012-06-07 15:19 · java · 编程语言 · Socket · Markdown

先贴上两段代码: 服务端ServerCode.class的 public class ServerCode {

public static int portNo = 3333;
public static void main(String[] args) throws IOException{
	ServerSocket ss = new ServerSocket(portNo);
	System.out.println("The Server is start: " + ss);
	Socket s = ss.accept();
	try{
		System.out.println("Accept the Client: " + s); 
		BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
		while(true){
			String str = in.readLine();
			if(str.equals("byebye")){
				break;
			}
			 System.out.println("In Server reveived the info: " + str);
             out.println(str);
		}
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		System.out.println("close the Server socket and the io.");
		ss.close();
		s.close();
	}
}

}

客户端 ClientCode的 public class ClientCode {

public static String clientName = "xiaodai";
public static int portNo = 3333;
public static void main(String[] args) throws IOException {
	InetAddress addr = InetAddress.getByName("localhost"); 
	Socket socket = new Socket(addr, portNo);
	try{			
		System.out.println("socket-----------"+socket);
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
		out.println("Hello Server,I am "+clientName);
		String str = in.readLine();
		System.out.println(str);
		out.println("byebye");
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		System.out.println("close the Client socket and the io.");
		socket.close();
	}
}

}

问题的引出: 首先说明下,这两段代码是我在网上下载的一篇学习socket编程上的,问题出现在客户端ClientCode这个类中,里面有这样两段代码out.println("Hello Server,I am "+clientName);和out.println("byebye");刚开始我没注意,把out.println写成了out.print,结果程序就卡住了,finally部分都执行不了,后面我仔细对照文章看了下,唯一不同的就是这了,所以抱着试试的心态改过来了,没想到居然就可以了。 一点想法: 通过这个例子我就在想,以前吧很少会注意print和println的区别,因为感觉他们的区别就是多了个换行,但在这里感觉print跟println区别挺大的,println比print多执行了一次按回车键的操作,因为只有这样才能解释当我们在控制台输入东西以后按回车键才能接收,用print就一直在输入状态,而没有提交状态。 呵呵,这是我自己的一点想法,或许这都不算个问题了,只是觉得自己第一次发现,或者第一次想到,所有记录下。欢迎批评指正。

评论(2)

  1. #2 楼 · lengyimeng · 2012-06-08 21:54

    ivorking writes:

    server端调用的是getline,只有当检查到\n时才认为结束 所以客户端,prinfln是会在字符串结尾自动补一个\n,所以程序正常执行

    谢谢

  2. #1 楼 · ivorking · 2012-06-07 22:38

    server端调用的是getline,只有当检查到\n时才认为结束 所以客户端,prinfln是会在字符串结尾自动补一个\n,所以程序正常执行

评论功能维护中,当前仅展示历史评论。