Java Socket : Write to client not working - java

I currently have a problem with a Java server thingy.
It's a simple TCP server which send images. Problem is, I don't have the code of the client program... Moreover, it seems that there is no way to check the client socket for writing event nor the amount of data already sent to the client.
Do someone have any idea about what could prevent the client to get the image correctly ?
Here's my code :
byte[] response = process ( cmd );
if ( response == null )
{
controlSock.close();
dataSock.close();
stop = true;
}
else if ( dataSock != null )
{
dos.write( response );
dos.flush();
}
By the way, the server is working fine with Telnet.

If the server works fine with telnet then your server is fine.
The problem is more likely to be in the assumptions the client is making are not the same as yours. for example the client might assume you are sending the size first in big or little endian format (as an int, short or long) Perhaps it expects the name of the file/image in some format as well.
The only way to know this for sure is to read the code for the client or ask someone who knows what assumptions the client makes.

Related

How to communicate with a python Twisted server from Java successfully?

These questions may sound silly, but I am new to this networking thing.
I have been trying for quite a few days now to implement a client that works with a Twisted server, but I am failing to get any response back from the server. I have read a lot of docs and watched a few tutorials and I got some of the stuff fixed and got some of the concepts better understood.
Before I step on to asking any questions, I wanna show you my code first. This is what I use to talk to the Twisted-based server:
val socketfactory: SocketFactory = SocketFactory.getDefault()
val socket = socketfactory.createSocket(host, port)
socket.keepAlive = true
socket.tcpNoDelay = true
val isSocketConnected = socket.isConnected //this checks socket's connectivity
val dOut = DataOutputStream(socket.getOutputStream())
val dIn = DataInputStream(socket.getInputStream())
val teststring = "Hi server!"
dOut.writeUTF(teststring)
Log.d("MILESTONE", "MESSAGE SENT AT THIS POINT, Socket is connected ?: $isSocketConnected")
var testreader = ""
while (true) {
testreader = dIn.readUTF()
Log.d("READING:", "RECEIVED THIS: $testreader")
}
My code seems to never get to the second "Log" line. It never gets there. I assume that's because I never get any input from the server. This is getting me confused. Because "socket.isConnected" returns true. Doesn't that mean there is an ongoing connection between the client (me) and the server ? But when I send any output the server doesn't talk back.
So my questions are:
1- Am I doing something wrong? Why do I receive no talk from the server and it blocks the code?
2- Is SocketFactory necessary ?
3- Is there any library that communicates with Twisted from Java ?
Thanks in advance !
For everyone who's struggling to communicate with a Twisted-running python server, I came with the absolutely best solution ever! After inspecting Twisted's open source code, I came to realize it has a "LineReceiver" class that only responds to a message if the line is finished. In other words, you can keep sending data forever and it will never respond until you finish the line and start a new one. Twisted will know the line has finished when a delimiter is used. (It is configured on the server-side). Most servers running Twisted will use a line delimiter : "\r\n"
That's the tricky thing! Once you send that little string, it will start responding to you. Here it is in an example :
val dOut = DataOutputStream(socket.getOutputStream()) //This is my favorite way of sending data!
val dIn = socket.getInputStream().bufferedReader(Charsets.UTF_8) //This is my favorite way of reading data !
val teststring = "hi server! \r\n" //This is the tricky part !
That's it ! all you have to do after that is read the lines from the bufferedReader, like this !
var testreader: List<String>
while (true) {
testreader = dIn.bufferedReader(Charsets.UTF_8).readLines()
for (line in testreader)
Log.e("MILESTONE", line)
}
After I started reading the input, I found out the server started actually sending me strings and communicating back with me. I hope everyone will get their codes working concerning this or any other thing!

Java - how sockets how can I receive data without constantly pinging

Okay, so I have an apache server that has text/data that I want to sendoff to a Java client. The issue is that the data will change often, and I don't want the client to constantly do a read on the server, because obviously I don't want a constant ping. I know that I can make a client socket but that requires my users to port forward to access the server, which isn't going to work for my users.
What I've found online is UDP punching may work or NAT Transfer, but I cant find any examples for how to do it in Java.
If you have any questions please feel free to comment :)
You could Recieve Server-Sent Event notifications, in which the server send the data, using PHP and JS as an example:
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
PHP:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Why did parseFrom() function hang using protobuf in java socket?

I just want to create echo server/client using protobuf and java.
I tested with protobuf-java-2.4.1 and jdk1.7.
I wrote echo server code like below
// create server socket and accept for client connection.
// ...
link = servSock.accept();
Person person = Person.parseFrom(link.getInputStream()); // blocking position
person.writeTo(link.getOutputStream());
I think it is not necessary to note Person.proto.
The client code is only send Person object using socket input stream and receive echo Person object.
// socket connect code was omitted.
Person person = Person.newBuilder().setId(1).setName("zotiger").build();
person.writeTo(echoSocket.getOutputStream());
person = Person.parseFrom(echoSocket.getInputStream());
But server was blocked in parseFrom function when the server and client both run.
I found if i use writeDelimitedTo() and parseDelimitedFrom(), then that is ok. I don't understand why the writeTo() and parseFrom() function does not working.
Why did the server blocking in there?
Is it necessary to send some end signal from client side?
The reason you have to use writeDelimitedTo()/parseDelimitedFrom() is that otherwise protocol buffers may have no idea how much data it needs to read from the socket. That presents a problem (I say may because you could of course create a message with only fixed length fields that wouldn't require this ... but protocol buffers has to deal with both cases)
The writeDelimitedTo() method writes the length of the message to the OutputStream then the message itself. Its counterpart parseDelimitedFrom() reads the length, then the message.
You can use writeTo() and pasrseFrom() with streams but only if you want to write/read a single message and are closing the stream after writing. The reader will then get an EOF to indicate the end of the message (also the case when reading from a file that contains only a single message).
Don't write your own Client/Server, ie. RPC solution. There is one here......https://code.google.com/p/protobuf-rpc-pro/ which has some nice features already for java.

Connect to socket on command line in Windows and send data

I want to connect to a number of different sockets/webservices on the command line and send data back and forth in the standard output/input.
I have been doing this using a variety of different languages and approaches so far: System.Net.Sockets in C#, flash.net.sockets in Flash and java.net.sockets in Java, depending on the protocol being used by the socket and the language being used in the client example given by the companies who've written the sockets. I've had enough of moving from language to language to do this (using the provided client socket example in each case), and will probably all the clients to java.
In the meantime, I want a way to connect to a socket on the command line in windows, see what's return in the standard output, send text to the socket on the command line (or a very, very simple GUI) and see what's returned back. I don't need any extra functionality like a periodic ping to keep the socket alive or anything.
What tools can I do this on Windows with? I've tried opening a telnet session to the socket i.e. push.domain.com 1234, and also tried using Putty to connect also, to no avail.
I'm trying to emulate the way a flash client connects to this socket and sends and receives data:
theSocket.addEventListener(Event.CONNECT, connectHandler);
theSocket.connect(theHost, thePort);
* * *
private function connectHandler(event:Event) : void
{
if (theSocket.connected)
{
bytes = new ByteArray();
bytes.writeByte(35);
bytes.writeByte(1);
bytes.writeByte(23);
bytes.writeByte(7);
bytes.writeUTFBytes(theTopic);
bytes.writeByte(0);
theSocket.writeBytes(bytes);
theSocket.flush();
theSocket.addEventListener(ProgressEvent.SOCKET_DATA, handshakeHandler);
* * *
private function handshakeHandler(event:ProgressEvent) : void
{
var zero:int = 0;
theSocket.removeEventListener(ProgressEvent.SOCKET_DATA, handshakeHandler);
theConnectionTimer.stop();
var bytes:* = new ByteArray();
var counter:int = 0;
theSocket.readUTFBytes(theSocket.bytesAvailable));
var a:* = theSocket.readByte();
var b:* = theSocket.readByte(); // the second byte should be 1????
var response:* = theSocket.readByte(); // this is the reponse identifier. . . ???
theMessageSize = theSocket.readByte(); // is this byte the size??????
switch(response)
{
case 100:
{
while ((zero = theSocket.readByte()) != 0)
{
var temp = counter++;
bytes[temp] = _loc_5;
};
theClientID = bytes.toString();
trace("The client ID is: " + theClientID);
How can I send the bytes values of 35, 1, 23, 7 and 0, as well as the value of the variable, Topic, to the socket using Hercules (or any other tool). Ideally, I'd like to connect with Hercules, send those bytes and the topic, and get something back containing the clientID like in the code. Although, I don't know if hercules will render the bytes in the response into text for me.
I'd appreciate any pointers at all on this.
Thanks.
I was thinking in Hercules and searching for the website I found out that there's already an answer here in stackoverflow.
I think it does what you need and more.
Uhm, I'm nost sure I understood completely what you are asking, but I don't see why telnet could not help you in this case.

Stop and wait socket programming with UDP

Looking to make a Java stop-and-wait UDP server and client but I'm running into some problems starting off. I've made a simple UDP client and server without the stop-and-wait part, but I would now like to learn how to change it. How can I send ACKs and implement timeouts using java sockets ?
Could someone please post up some examples for me to use in my implementation ?
If you're implementing this in UDP, sending and receiving acknowledgements is up to you. This seems to be what you want for this stop and wait protocol. In terms of pseudocode, you would want something like:
int Send(msg)
{
char rcvBuf[];
sentBytes = sock.send(msg);
sock.rcv(rcvBuf);
return sentBytes;
}
int Recv(rcvBuf)
{
String ackMsg = "ACK";
length = sock.rcv(rcvBuf);
sock.send(ackMsg);
return length;
}
After every send, you wait for an acknowledgement message to come in, and every time you receive, you send an acknowledgement.

Categories