【发布时间】:2011-11-06 23:32:08
【问题描述】:
我要做的是从套接字连接中读取数据,然后将所有数据写入文件。我的读者和所有相关陈述如下。任何想法为什么它不起作用?如果您能找到一种更有效的方法来执行此操作,那也会很有用。
(我的完整代码确实成功连接到套接字)
编辑:添加了更多我的代码。
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");
}
【问题讨论】:
-
skt是干什么用的?连接到自己?为什么?你为什么不在sc,接受的SocketChannel 上做任何I/O?
标签: java file sockets inputstream bufferedreader