Results 1 to 4 of 4
Thread: Reading From Socket
- 07-27-2011, 10:23 AM #1
Member
- Join Date
- Jul 2011
- Posts
- 3
- Rep Power
- 0
Reading From Socket
Hello!
Now I am trying to make a simple server that will read data from the client.
Client is a device that tries to establish a connection to the server by sending it <INI> string. If there is no answear from the server device will send <INI> string back in 5 minutes.
Here is my code:
As I expect this program has to print <INI> every time device tries to establish a connection. But in fact it only prints <INI> one time!Java Code:import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ServerSide { private static final int PORT = 28001; public static void main(String[] args){ try{ ServerSocket server = new ServerSocket(PORT); //Server listens to port # 28001 Socket clientSocket = server.accept(); String inputLine; BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true){ inputLine = in.readLine(); System.out.println(inputLine); if(inputLine == null) break; } in.close(); clientSocket.close(); }catch (IOException ex){} }
Why other <INI> - s are not printed? What is wrong with the way I read data from the socket?
- 07-27-2011, 02:00 PM #2
The code you've posted only has one accept for one connection. The next time the client tries to make a connection, the server is not listening for a new connect.program has to print <INI> every time device tries to establish a connection.
Put the accept in a loop. When there is a connection, create a new thread to handle each incoming connect separately.
- 07-27-2011, 02:37 PM #3
Member
- Join Date
- Jul 2011
- Posts
- 3
- Rep Power
- 0
Thanks a lot! I forgot about it.
- 07-28-2011, 12:47 AM #4
Also, when the client disconnects, the InputStream will treat it as end-of-file and readLine() will return null. You don't really need to put that in a loop if the client is only sending one line, because readLine() will not return until it reads a line. (Unless you've set a socket timeout.)
Get in the habit of using standard Java naming conventions!
Similar Threads
-
Problem reading from server socket
By glauber in forum Advanced JavaReplies: 5Last Post: 02-17-2011, 12:11 PM -
Socket and how to launch thread for receiving socket messages
By newbiejava in forum New To JavaReplies: 1Last Post: 07-02-2010, 01:18 PM -
Reading inputstream on socket
By javanetworknew in forum NetworkingReplies: 1Last Post: 04-27-2010, 11:01 AM -
Problem reading from socket using read(bytes[])
By sm123 in forum New To JavaReplies: 1Last Post: 04-21-2010, 06:49 PM -
Reading Web Pages with Socket Channels
By Java Tip in forum java.netReplies: 0Last Post: 04-07-2008, 08:00 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks