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

关于Socket的一个问题
Java code
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

/**
  *send string to each connected client
  */
public class MainClass4 extends Thread
{
    Socket socket;

    public void run()
    {
        try
        {
            String s="I am a server.";
            PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
            pw.println(s);
            socket.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
    /**
      *main entry
      */
    public static void main(String[] args)throws Exception
    {
        ServerSocket ssock=new ServerSocket(8080);
        while(true)
        {
            Socket esock=null;
            esock=ssock.accept();
            System.out.println("Connected");
            MainClass4 t=new MainClass4();
            t.socket=esock;
            t.start();
            esock.close();
        }
    }
}

这是服务器端程序,向连接到此服务器的客户端发送一段字符串,下面是客户端程序:
Java code
import java.io.*;
import java.net.*;
/**
  *MainClass4 Client
  */
public class MainClass4Client
{
      /**
        *mian entry
    */
    public static void main(String[]args)throws IOException
    {

        Socket sock=null;
        BufferedReader bin=null;

        try
        {
            sock=new Socket("localhost",8080);
            bin=new BufferedReader(new InputStreamReader(sock.getInputStream()));
        }
        catch(UnknownHostException e)
        {
            System.err.println("Don't know about host localhost");
            System.exit(1);
        }
        catch(IOException e)
        {
            System.err.println(e);
        }
        
        System.out.println(bin.readLine());
        bin.close();
        sock.close();
    }
}

但是客户端运行结果却是:
null
End
,请问这是怎么回事,客户端怎么没有读取到服务器端发送的字符串呢?

------解决方案--------------------
加上pw.flush()试试、
------解决方案--------------------
服务端不要把sock关闭了