What I am trying to do is to read in data from a socket connection then wr开发者_如何学JAVAite all of that to a file. My reader and all the related statements are below. Any ideas why it is not working? If you can see a more efficient way to do this that would also be useful.
(My full code does successfully connect to the socket)
EDIT: Added more of my code.
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");
}
You program requires you to type in a line for every line you read from the socket. Are you typing enough lines?
The lines you read from the console are written to the file, did you expect the lines from the socket to be written to the file?
Where are you closing the file (and the socket)
Another approach is to use a utility like Apache IOUtils
Socket skt = new Socket("localhost", port);
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename));
skt.close();
I think there's a typo in this line:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
Change "System.in" to just "in":
BufferedReader stdIn = new BufferedReader(new InputStreamReader(in));
FYI, here is how I like to read sockets. I prefer to avoid the string encoding offered by the readers, and just go straight for raw bytes:
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();
Oh, cute, turns out that code is essentially what IOUtils.copy() does (+1 to Peter Lawrey!):
http://svn.apache.org/viewvc/commons/proper/io/trunk/src/main/java/org/apache/commons/io/CopyUtils.java?view=markup#l193
精彩评论