Skip to main content
GameDev.net gamedev.net
🔒 Locked

Java sockets, message won't send unless I close the socket

Started by johnnyBravo Sep 15, 2007 at 5:51 AM 5 replies 4.4k views
Original Post
johnnyBravo
johnnyBravo
When I'm sending messages it will not actually send the text unless I close the connection, but I need to send multiple messages back and fourth during a single connection. heres my source:

Socket socket = new Socket("localhost", 3333);
				
DataOutputStream o = new DataOutputStream(socket.getOutputStream());
o.writeBytes("hello");

//closing it is the only way to get it to send, using either
o.close();
//or
socket.close()

The receiver source is

ServerSocket listenSocket = new ServerSocket(3333);
BufferedReader inFromConn = new BufferedReader(new InputStreamReader(socket.getInputStream()));						
while(!inFromConn.ready());

System.out.println(inFromConn.readLine()); //isn't called until the connection is closed

thanks
let_bound
let_bound
Isn't DataOutputStream buffered? If so, that'd be your problem. Calling flush() would probably do what you want.
OrangyTang
OrangyTang
IIRC the Socket class uses a tcp connection, which will be buffered. A flush() call should cause it to send any pending data.

Remember that tcp is a stream protocol, not a packet protocol. That means that your "messages" may be split up or merged by the time they reach the other end of your connection. (See Q14 in the network forum faq http://www.gamedev.net/community/forums/showfaq.asp?forum_id=15 ).
rip-off
rip-off
The data is probably being buffered. Try calling flush().
johnnyBravo
johnnyBravo
I tried flush(), but it did seemingly nothing.


edit:
I got it working with this:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);out.println("hello");


I'm not sure what the difference between the two output clases, but it works how i want.

[Edited by - johnnyBravo on September 15, 2007 7:41:34 AM]
leidegren
leidegren
Are you really fulshing the right stream? becuase were ever you have a buffer you must flush inorder to get an immidate send. Make sure you call flush on the outer most enclosing stream, otherwise you might as well be doing nothing. And if it doesn't work something is really really wrong.
Barius
Barius
Quote:
Original post by johnnyBravo
I'm not sure what the difference between the two output clases, but it works how i want.


The difference is the newline written by println. The readLine method waits for a newline. If you had used writeBytes("hello\n"), your first example would have worked (I think).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.