PrintWriter Sockets Stop responding after 1 time of sending data - java

Hello there. I am trying to send data from client to server, the first time it works, but the second time it stops getting the data. I don/t know what's wrong.
http://pastebin.com/Sc72aAqD
Basically it is a simple key logger, the wierd part is that it works for the first time, but the second time it doesn't get's response from the client.

It looks like you have a loop on the Client that reads lines from the server, and if the line is some particular String, you send a String back to the server.
On the server, it looks like you're reading 15 lines from the client. But I don't see anything that the server is sending back to the client. Wouldn't the client just block at:
while ((Client.f = in.readLine()) != null) {

Related

Java sockets, server send message to multiple clients

I am one server and multiple clients via threads. The client(s) send their message to the server. I have worked out how to make the server send the message back to client like a echo system. If I have two clients, I want them to send their message to the server and the server should send it to the client that did not send the message i.e. the other client. How would I go about send the message back to all the clients apart from the one that send the message?
When the message comes in, determine what the userID / other identifying id the incoming message is associated with. Then re-broadcast to all other sockets, but exclude the Socket associated with the ID that sent the message
Make at the server side a list with all the clients...
every time a new msg is received, then iterate the list and send the msg using the port of the socket as id...
I recently wrote a Chat program too. What I did was, I had a class ClientHandler that handles the connection for each individual client.
Inside ClientHandler I had a HashMap. I added each client that had connected to the HashMap, with the Key being the client id. I used a UUID rather than int for the client id.
Inside this handler class, I had a sendMessage(String str) method. Within this method, a for-each loop that loops through each ClientHandler object, checking the values inside the HashMap. Inside this for-each loop, I have an if statement that checks whether you are writing to the ClientHandler object with this id. If the check returns false, you go ahead and write the message on the PrintWriter and the message won't be sent to the client writing the message.
This worked for me. Might not work for you.

While loop not continuing - socket

Okay, so I'm creating a rather simple java application, which will eventually turn into an online 2-player texas hold'em game. Right now, I'm trying to send some simple messages over network to make sure the basic functionality is working. I am however stuck.
I've got two methods in a class. One for the serverside (or really a hybrid between a client and a server), and one for the clientside. They connect together fine. As I made this, I noticed that when I connected, they both spammed their default messages (right now being "CLIENT: Started" and "SERVER: Started" back and forth to eachother. I figured this was because the string containing that information was never emptied, and so they never knew when to stop transmitting it. I then made sure that after sending the message, that variable was nulled, and a check was made to see if it was null before sending.
Here's where it went wrong though! After doing that, they won't send more than one message at all. They send their respective welcome messages, but anything I try to transmit after that is ignored. It's almost like if the while-loop for the server/client stops.
So, I have two public variable declared in the class. These contain any message the server or client wishes to send.
public static String serverCommand = null;
public static String clientCommand = null;
They are null by default, but changed during runtime in the GUI-part.
The server loop looks like this:
while(true)
{
if((receive = receiveStream.readLine()) != null)
{
System.out.println(receive);
}
if(serverCommand != null)
{
printer.println(serverCommand);
printer.flush();
Network.serverCommand = null;
}
}
And the client while loop like this:
while(true)
{
if(Network.clientCommand != null)
{
printer.println(clientCommand);
printer.flush();
Network.clientCommand = null;
}
if((receive = receiveStream.readLine()) != null)
{
System.out.println(receive);
}
}
However, as mentioned - after Network.clientCommand is set to null the first time around, it never again sends any messages, even though Network.clientCommand changes due to user input during runtime.
I'll post two links to the complete sourcecode of the client/server-part of this below, as they're a bit too big to paste here.
LINK: http://hastebin.com/oqotirufic.java
Does anyone here have any idea what's happening, and how should I think when trying to fix/get around it? I'll add that my experience with both Java and network programming is very limited.
EDIT
I'll add the part of the GUI which acccesses/changes the variables.
http://hastebin.com/upadayuwug.java
Of course after Network.clientCommand is null, nothing more is sent — that's what you told it to do:
if((receive = receiveStream.readLine()) != null)
{
System.out.println(receive);
}
According to the JavaDoc, readLine() returns
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Not "null if there's a pause in transmission". If it hasn't yet seen a full line, or the end of the stream (socket disconnection), well, then it's not done yet. It waits until it gets the full line of input before it goes to the next line of your code.
But how do you know if you should wait for a message to come in, or send out the next one? You can't. You can't depend on when or if anything will arrive from the other side.
What happens when both sides have nothing to send? They both start waiting to receive. What happens when one side gets something new to send? Well, once it receives something, it'll send it. But that never happens!
What you can do, is call readLine() in a separate thread. See the JavaDocs for Thread and the Java Tutorial Lesson "Concurrency". And if you're using Swing for your GUI, also see the Java Tutorial Lesson "Concurrency in Swing".

Java Sockets: Request-response pattern with object streams

My objective is to implement a simple request-response pattern based on Java sockets
that is used to request an object from a server.
It should work like this:
The client sends a message to the server, which the server evaluates. Depending on what
he received, a certain function is called. This part works.
The server writes the requested data into the ObjectOutputStream. This also works, at least
I didn't receive an error.
The client reads the data from the input stream until he receives a CLOSE message which makes the
program quit the while-loop. This does not work as it should.
Here are some critical code fragments:
// Client (Sending request) *** WORKS
objectOutputStream.writeInt(GET_OBJECT);
objectOutputStream.flush();
// Server (After receipt of the message) *** WORKS
objectOutputStream.writeInt(object);
objectOutputStream.writeInt(CLOSE);
// Client (Reading the answer from the server) *** WRONG
while(true){
int i = objectInputStream.readInt();
if(i == CLOSE)
break;
}
You have flush at the client side, and the message is received by the server;
you lack flush at the server side, and the message is not received by the client.
I notice a pattern in these two facts...

A reliable way to read socket data

The application that I am working on has two parts. The server part runs on a Linux machine. The client part, an Android application, queries the server and gets necessary response. Both the parts are written in Java, use socket-based communication, and transfer textual data.
Right after sending the request, here is how the client receives the response:
public static String ReadAvailableTextFromSocket(BufferedReader input) throws IOException {
if (input.ready() == false) {
return null;
}
StringBuilder retVal = new StringBuilder();
while(input.ready()) {
char ch = (char) input.read();
retVal.append(ch);
}
return retVal.toString();
}
However, this doesn't seem to be that reliable. The input is not always ready because of server response time or transmission delays.
Looks like input.ready() is not the right way to wait for getting data.
I am wondering if there is a better way to accomplish this. Perhaps there is some standard practice that I could use.
Perhaps you should use Threads. Keep a listener thread in a while(true) loop that reads more data as it comes in, and simply buffers the data in a data structure (let's say a queue) shared with the main thread. That way, the main thread could simply dequeue data as needed. If the queue is empty, it can infer that no new data was received.
Edit: see this multithreaded chat server/client code as an example.
Here is how I solved this problem. As I am responsible for writing both, the client side as well as the server side, when a request comes to the server, the first line of information I send as the response is the number of bytes the client can expect. This way, the client first waits to read a line. Once the line is read, the client now knows how many bytes of data to expect from the server.
Hope this helps others.
Regards,Peter

Winsock only sending data at program close

I have a c++/windows program that receives data from another c++ program via a WM_COPYDATA message. It is then supposed to use Sockets/winsock to send this message on to a server written in Java. The client connects to the server fine, but it doesn't seem to be able to send messages in a timely fashion. However, once the client is closed down, all the messages it should have been sending get sent in one big lump. Here is an example of the terminal output of the Java server:
Server Starting up.
Client Accepted.
hi from clienttesttesttesttesttesttesttesttesttesttesttesttesttesttest
the first two lines are output by the Java server when those events happen. The last line is messages from the client. The client sends "hi from client" right after winsock is initialized, and then "test" at various points later in the program as it receives data from the other c++ program via WM_COPYDATA messages.
Here is the Java server code:
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String incomingLine;
while((incomingLine = in.readLine()) != null)
System.out.println(incomingLine);
Here is the c++ function where the messages are sent:
void sendDataWinsock(char* text){
int result = send(ConnectSocket,text,(int)strlen(text),0);
}
And here is a section of WndProc where the WM_COPYDATA messages are processed:
case WM_COPYDATA:
sendDataWinsock("test");
break;
Does anyone know why it is doing this? It is as if the client program is adding all these messages to a queue of things it should be sending, but is too busy to send them immediately, and so only sends them as the program is closing down, when it no longer has to process Windows messages. Or, I suppose, the error could actually be in the Java code - I am fairly new to this.
You are reading lines on the server, but you are not sending lines.
That means your server sits there, receiving data but waiting to return a line of text back to your program from readLine() , which does not happen since no newlines , \n, gets sent. When the client exits, readLine() gives you back the data it read thus far.

Categories

Resources