I am having a real problem trying to find a solution to my problem and hope you guys could help. I have seen many socket examples online but have been unable to modify them for my use. Tbh, im struggling to even get an understanding of sockets. What I have been able to modify so far is below.
My problem, I believe is that my client program is not reading the incoming message from the server, could someone use my example to demonstrate where I am going wrong. Something in my mind tells me that my client socket closes before having a chance to read any incoming message. perhaps getting the client to wait until a message is recieved? If waiting is what is needed, how is this achieved? Thanks in advance.
CLIENT:
try {
Socket socket = new Socket("localhost", 55555);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write(score);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String rank = in.readLine();
System.out.println(rank);
in.close();
out.close();
socket.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
SERVER:
try {
System.out.println("Waitng for client to connect.....");
ServerSocket server = new ServerSocket(55555);
Socket socket = server.accept();
System.out.print("Client has connected!\n");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String score = (in.readLine());
scor = Long.parseLong(score);
leaderboard(); ///// A METHOD THAT USES LONG SCORE TO CALCULATE RANKING- RETURNS A STRING VALUE CALLED RANK
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.print("Sending rank: " + rank);
out.write(rank);
out.close();
socket.close();
server.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n")`enter code here`;
}
Your code looks fine...
On your client program you're writing a line using:
out.write(score);
could you change this to:
out.println(score);
Also do the same on your server's program to take care of the reply:
out.println(rank);
Let me know how you go..
also if this helped, don't forget to upvote/mark this as a solution ;)
cheers
(Btw,as to what caused the problem:: in.read'LINE'() waits for the end of a line or newline(\n) for the string value to be saved. if you use out.write() then you have to and a newline character(\n) manually for the string to be read completely. if you use out.printline, then \n is added automatically to every string sent.
The readline method in your program was waiting for a newline character, which is why your program was stuck in that spot)
Related
I've edited the code to explain that better.
I've got Android application, which is client and Java server. I'm trying to send info from client to server, process that information and send the result back to client.
I'm using BufferedReader, InputStreamReader and DataOutputStream to send and receive messages.
So my Client.java has this code:
try {
//Sending message to server
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
outToServer.writeBytes(messageString + '\n');
outToServer.flush();
} catch (IOException e) {
System.err.print(e);
}
try {
System.out.println("This line is showing");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String res;
System.out.println("And this line is showing");
res=inFromServer.readLine();
System.out.println("But this never is");
System.out.println("Received: " + res); //This line is never printed in console
}catch (IOException e) {
System.out.println(e);
}
And my Server.java has this:
try{
System.out.println("Creating InputStream");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = inFromClient.readLine();
System.out.println("Received: " + message); //correct string received
} catch (Exception ex) {
System.out.println("Creating InputStream failed");
System.err.print(ex);
}
try{
String response = "Response from server"
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
outToClient.writeBytes(response + '\n');
outToClient.flush();
System.out.println("Sent to client: " + response); //correct string is showing in console
} catch(Exception ex) {
System.out.print("Error! " + ex);
}
The thing is that my server gets the message correctly, as understandable string. It shows in console what it's sending to client and that also is understandable string.
But when I'm trying to get the message at client it does nothing.
inFromServer.readline() isn't throwing any exception to console and I don't know why it's not working.
I tried inFromServer.toString(), and then I received something, but it definitely wasn't the string sent from server. It was something like:
java.io.BufferedReader#b3d109a0
I don't know what I'm doing wrong. The sending/receiving function is called from login function, which is called from onPostExecute. I don't know how can do this from doInBackground.
BufferedReader.readLine() isn't working
Oh yes it is. Your error is in trying to convert the reader into a string, instead of using the line that was read.
Yo should remove the ready() test. It is pointless.
You should also use symmetrical streams. If you use Readersat one end you should use Writers at the other, such as BufferedWriter. Not DataOutputStream.
I suggest that this isn't the real code, and that there isn't a \n on the end of the sent message, which would explain readLine() blocking until the non-existent line terminator arrives, but you should redo this using BufferedWriter instead of DataOutputStream as mentioned above.
So I'm having some serious problems with Java's server side socket, which accepts connection, but it can't read anything from BufferedReader, which I have put to read the text stream from socket connection. Code for my threads run(), which I'm creating and running at the first time when any page is loaded.
public void run() {
try{
ServerSocket s = new ServerSocket(4100);
System.out.println("New tcp socket created");
Socket socket = s.accept();
System.out.println("New tcp update connection established.");
InputStream din = socket.getInputStream();
PrintWriter outp = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
System.out.println("Streams created");
String inputline = "nothing yet...";
outp.println("hello from server");
while(true){
System.out.println("Got input from client:" + inputline);
inputline = in.readLine();
if(inputline == null || inputline.equals("exit")){
break;
}
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Updater thread exits.");
}
This prints out everything properly, except for Got input from client: + what ever my client sends with PrintWriter which outputs to a socket.
Client side example:
Socket s = new Socket(serverip, serverDownloadsUpdatePort);
OutputStream dout = s.getOutputStream();
PrintWriter outp = new PrintWriter(dout);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());//This prints out properly, what server sends to client
outp.println("test connection");
outp.println("Can you hear me?");
outp.println("exit");
s.close();
Your client may not be sending end-of-line characters along with its input, causing your server to wait indefinitely at "in.readLine()".
The Javadoc for BufferedReader's readLine method (http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) says: "Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed." Make sure that your client is sending input that conforms to this rule.
I was able to see client input using your server with the following client Runnable (but only if I include the "\n"):
public void run() {
try{
Socket writeSocket = new Socket("localhost", 4100);
PrintWriter out =
new PrintWriter(writeSocket.getOutputStream(), true);
out.write("Hello there!\n");
out.flush();
}
catch(Exception e){
e.printStackTrace();
}
}
EDIT: When using println as in the submitter's client example, you don't need to worry about adding "\n", but you do need to flush the socket. One way to make sure this happens is by setting autoFlush=true in the PrintWriter constructor.
I found out that I forgot to set PrintWriter as auto flushable at client side and thats why it didn't work becouse stream didn't got flushed at any time.
I did a Java Socket server, and a C++ Client.
However, the client connects to the server, without problems.
But when I write something client-server, the server doesn't catch the message.
What I'm doing wrong?
A little bit of the code of the Java Server:
DataInputStream dis=new DataInputStream(usrSocket.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while((data = dis.read())>=0) {
out.write(data);
}
byte[] bytes = out.toByteArray();
String decrypt = new String(bytes);
if(decrypt.equals("status")){
System.out.println("Status emitted.");
}
System.out.println("Received a message.");
C++ Client writing:
QByteArray qba;
qba.append(text);
sock->write(qba.data());
qDebug() << "Send status";
I need help with that, thank you very much.
(that variable "text" it's a QString)
EDIT
Java server: That's only one part of all the code, the main thread waits for connections (Socket sock = server.accept()) and create a new thread for each user.
The code that I published of the java server, its one part of that threads for the users.
If you need ALL the code, plese tell me.
I will be waiting the answers!
Thank u very much!
Sorry if I answer ya late.
Try this code for Java Server.
ServerSocket ss = new ServerSocket(Port_No);
Socket incomingClient = ss.accept();
InputStream i = incomingClient.getInputStream();
OutputStream o = incomingClient.getOutputStream(); // Use it write to the Client Socket
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = new String();
while ((str = br.readLine())!=null){
// do what you want with the data received in str.
}
As youre using QTcpSocket, it highly likely that you are running the client in the default asynchronous mode. This means after when you write after calling connectToHost, nothing will be sent as the socket is not connected.
Try using:
socket->connectToHost(hostAddress, hostPort, QIODevice::ReadWrite);
if (socket->waitForConnected()) {
QString text = "test string";
QByteArray array;
array.append(string);
qDebug() << socket->write(array);
} else {
// connect error!
}
Your Java code reads the socket until EOS and then prints something, which by the way is not a decryption operation. Your C++ client writes something and never closes the socket. So the server can never get out of the read loop.
If I read it correctly it is caused by the fact that your client is still running. Read() returns number >= 0 until the client socket is closed.
I created an application which establishes connection with the given port and transport data either ways. But I am having issues in reading the data from the server.
try{
Socket skt = new Socket(127.98.68.11, 1111); // connecting to this to get data
String message = "some test message";
if(option.equalsIgnoreCase("send")){
OutputStream outToServer = skt.getOutputStream();
outToServer.write(message); // this is working, message stored on server-side
}else if(option.equalsIgnoreCase("receive")){
BufferedReader in = new BufferedReader (new InputStreamReader(sit.getInputStream()));
String fromServer = in.readLine();
System.Out.Println(fromServer);
}
}catch(IOException io){
io.printStackTrace();
}
In this program everything is working as expected. except in.readline().
I tried running this program in debugging mode, and the by the time compiler reaches this command. is was doing nothing and i can't see the cursor also
It could be because you are trying to do an in.readLine() this requires that the server terminates the "receive" command which it is sending to the client with a newline.. "\n" or "\r\n" along
I am writing a client application that will receive a continuous flow of data through tcp/ip. The problem I'm having is that the buffered reader object isn't receiving any data and is hanging at the readline method.
The way the server works is that you connect to it, and then send authentication information in order to receive data. The gist of my code is below
socket = new Socket(strHost, port);
authenticate();
inStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
process(inStream);
authenticate()
{
PrintWriter pwriter = new PrintWriter(socket.getOutputStream(), true);
pwriter.println(authString);
}
process(BufferedReader bufferedReader)
{
while((line = bufferedReader.readLine()) != null)
dostuff
}
I created a sample server application that sends data the way (I think) the server is sending data and it connects, and receives and processes the data fine. I can connect to the server fine in my application. I can also telnet to the server and write the authentication string and receive a flood of data using telnet. However my application just hangs at readLine with the server and I'm out of idea's why.
The data coming in (through telnet atleast) looks like a continuous stream of the following:
data;data;data;data;data
data;data;data;data;data
Why is my app hanging at readline, am I not outputting the authentication line correctly? I'm not receiving any errors...
EDIT
My sample server code (which is working correctly)...again this is only mimicking the way I think the real server is running but I can connect to both in my application just not receive data from the real server.
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(1987);
}
catch (IOException e)
{
System.out.println("Couldn't listen on port: 1987");
System.exit(-1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println("Accept failed: 1987");
System.exit(-1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String something;
while ((something = in.readLine()) != null)
{
while(true)
{
out.println(message);
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
Firstly you should call BufferedReader.ready() before calling readLine(), as the ready() will tell you if it's ok to read.
PrintWriter doesn't throw I/O Exception so the write may have failed without your knowledge which is why there is nothing to read. Use PrintWriter.checkError() to see if anything as gone wrong during the write.
You ought to set up the input and output streams on the Socket at the same time before you write anything down the pipe. If your reader is not ready when the other end tries to write you will get a broken pipe in the server and it won't send any more data. Telnet sets up read and write before you have written or read anything.
You can make use of Wireshark to tell if the server is actually sending data.
BufferdReader.readLine() reads lines, i.e. sequences of characters ended with \r or \r\n. I guess that your server writes its output into one single line. Your telnet output proves this assumption. Just use PrintWriter.println() at server side.
this work with me
with socket without flush
void start_listen()
{
String result1="";
char[] incoming = new char[1024];
while (!s.isClosed())
{
try {
int lenght = input.read(incoming);
result1 = String.copyValueOf(incoming,0,lenght);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.d("ddddddddddd",result1);
}