日期:2014-05-20  浏览次数:20770 次

Java Socket入门案例求解
Server.java代码如下:
Java code

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args)throws Exception {        
            ServerSocket server = new ServerSocket(1331);
            Socket  socket  = server.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String fromClient;            
            while((fromClient = in.readLine()) != null){                
                System.out.print("message form client:"+fromClient+"\n");
            }    
    }
}


使用telnet连接上去之后,每次输入字符,都会在服务器端控制台显示。
如何编写一个客户端的程序,使它能够实现telnet这个效果呢?
我编写的客户端代码如下,该效果只能在客户端关闭在socket的连接时,服务器端才会将客户端的所有输入显示在控制台?
这是什么原因呢?如何解决呢?
求高手指点,谢谢!
Java code

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws UnknownHostException, IOException {
        
            Socket socket = new Socket("127.0.0.1",1331);                    
            OutputStream out = socket.getOutputStream();
            Scanner sin = new Scanner(System.in);
            while(sin.hasNextLine()){                
                out.write(sin.nextLine().getBytes());
                out.flush();            
            }
            out.close();
            socket.close();
    }
}



------解决方案--------------------
呵呵,问题就出在Server的“in.readLine()”

你把Client的代码修改下,这句话:
out.write(sin.nextLine().getBytes());
改为:
out.write((sin.nextLine() + "\n").getBytes());

相信你能理解为啥了。