2011-08-30 97 views
1

我想要做的是从套接字连接读取数据,然后将所有这些写入文件。我的读者和所有相关的陈述如下。任何想法,为什么它不工作?如果你能看到更有效的方法来做到这一点,那也是有用的。如何从套接字读取数据并将其写入文件?

(我的全代码没有成功连接到插座)

编辑:添加更多的我的代码。

public static void main(String args[]) throws IOException 
{ 

    Date d = new Date(); 
    int port = 5195; 
    String filename = ""; 
    //set up the port the server will listen on 
    ServerSocketChannel ssc = ServerSocketChannel.open(); 
    ssc.socket().bind(new InetSocketAddress(port)); 

    while(true) 
    { 

     System.out.println("Waiting for connection"); 
     SocketChannel sc = ssc.accept(); 
     try 
     { 

      Socket skt = new Socket("localhost", port); 
      BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
      FileWriter logfile = new FileWriter(filename); 
      BufferedWriter out = new BufferedWriter(logfile); 
      BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 

      while ((inputLine = stdIn.readLine()) != null) 
      { 
       System.out.println("reading in data"); 
       System.out.println(inputLine); 
       out.write(inputLine); 
       System.out.println("echo: " + in.readLine()); 

      } 

      sc.close(); 

      System.out.println("Connection closed"); 

     } 
+0

什么是'skt'?连接到自己?为什么?为什么你不在'sc'上接受SocketChannel的任何I/O? – EJP

回答

1

您的程序要求您为从套接字读取的每一行输入一行。你输入的行数是否足够?

您从控制台读取的行会写入文件,您是否期望将套接字中的行写入文件?

你在哪里关闭文件(及插座)

另一种方法是使用一个工具,如Apache IOUtils

Socket skt = new Socket("localhost", port); 
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename)); 
skt.close(); 
+0

所以我尝试了这一点,但仍然没有数据被写入文件。我打开这样的端口: 'ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket()。bind(new InetSocketAddress(port)); \t \t而(真) \t \t { \t \t \t \t \t \t \t的System.out.println( “等待连接”); \t \t \t SocketChannel sc = ssc.accept();' – Andrew

+0

看起来很好。如果你通过telnet连接到服务器,你会看到你期望收到的数据吗? –

0

我认为有在这一行一个错字:

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 

将“System.in”更改为“in”:

BufferedReader stdIn = new BufferedReader(new InputStreamReader(in)); 

仅供参考,这里是我喜欢读取套接字的方式。我宁愿避免被读者所提供的字符串编码,只是直行原始字节:

byte[] buf = new byte[4096]; 
InputStream in = skt.getInputStream() 
FileOutputStream out = new FileOutputStream(filename); 

int c; 
while ((c = in.read(buf)) >= 0) { 
    if (c > 0) { out.write(buf, 0, c); } 
} 
out.flush(); 
out.close(); 
in.close(); 

哦,可爱的,原来,代码基本上什么IOUtils.copy()不会(+1彼得Lawrey !):

http://svn.apache.org/viewvc/commons/proper/io/trunk/src/main/java/org/apache/commons/io/CopyUtils.java?view=markup#l193

相关问题