I have very simple java server:
int port = 2245;
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
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){
System.out.println("str = " + str);
o.write(123); //("message from server");
}
} catch(Exception x) { x.printStackTrace(); }
And I have simple Qt client, that use QNetworkAccessManager
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl url("http://127.0.0.1:2245");
url.port(6666);
QByteArray postData;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QString postKey("SomeKey");
postData.append(postKey);
QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));
I declared in mainwindow.h in slot replyFinished
public slots:
void replyFinished(QNetworkReply* reply);
In best case Server get some headers like(POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded and others)
But on server I can not read my message from client
and client does not receive ANY response from java server
The correct code for Qt client is this:
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl url("http://192.168.0.101:8000");
url.port(8000);
QByteArray postData;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QString postKey("some data");
postData.append(postKey);
QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));
manager->post(request, postData);
}
and to get response declare and implement the following slot
void MainWindow::replyFinished(QNetworkReply *reply){
qDebug() << "Status" << reply->errorString();
qDebug() << "Status" << reply->error();
QByteArray data = reply->readAll(); //It's works!
qDebug() << "data: " << data;
}
For server side I have used HttpServer, which is available in latest version of JDK
Related
I need to write a program using Java to connect a socket, send authenticate data and receive the answer. I have a code in Python that works and I'm using this as an example.
I'm able to connect but after send data I didn't receive anything.
Below the java code that I wrote:
String hostname = "remoteHost";
int port = 4200;
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");
out.write(json.toString());
System.out.println(in.readLine());
Below the example in Python:
import socket, json
from dateutil import parser
host = "app.sensemetrics.com"
port = 4200
apiCode = "YourAPIKey"
# Open a new socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# Send the authentication request
handshake = json.dumps({
"jsonrpc": "2.0",
"method": "authenticate",
"params": {
"code" : apiCode
},
"id": 0
})
s.send(handshake)
# Parse the response
jsonFrame = decodeOneJsonFrame(s)
response = json.loads(jsonFrame)
print("\r\nHandshake Exchange:\r\n" + " --> " + handshake + "\r\n" + " <-- " + jsonFrame)
# Close the socket connection
s.close()
out.write(json.toString());
I think you should also call out.flush().
Don't forget to call flush on other side too, after writing response so you can read it with System.out.println(in.readLine());
See here
Use try-with-resources to automatically close open resources and OutputStream.flush - to flush the data to the stream.
Modify your code as below:
String hostname = "remoteHost";
int port = 4200;
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");
try (
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
out.write(json.toString());
out.flush();
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
I'm trying to answer the clients message with an echo, but I am not figuring how to. My client sends a message, but then I reverse the papers and the program doesn't proceed (gets stuck in line
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
of the server). I guess it is about closing the inputstream, but when I do that, that closes the socket and I have no way to reuse it. I have managed do do this with readUTF and with socket.shutDownInput, but I want a easiest way - like close or flush, which I am not getting.
Client
public class SocketClient {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 3) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s host port file%n", SocketClient.class.getName());
return;
}
String host = args[0];
// Convert port from String to int
int port = Integer.parseInt(args[1]);
// Concatenate arguments using a string builder
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]);
if (i < args.length-1) {
sb.append(" ");
}
}
String text = sb.toString();
// Create client socket
Socket socket = new Socket(host, port);
System.out.printf("Connected to server %s on port %d %n", host, port);
// Create stream to send data to server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// Send text to server as bytes
out.writeBytes(text);
out.writeBytes("\n"); // devia meter readline a null...
System.out.println("Sent text: " + text);
System.out.println(socket.getInetAddress().getHostAddress() + " " + socket.getPort());
//out.close();
//socket.shutdownOutput(); trials...
////////////////////////////////////////////
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("here");
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response); // here is where client doesn't proceed - he doesn't get the echo
Server
public class SocketServer {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 1) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s port%n", SocketServer.class.getName());
return;
}
// Convert port from String to int
int port = Integer.parseInt(args[0]);
// Create server socket
ServerSocket serverSocket = new ServerSocket(port);
System.out.printf("Server accepting connections on port %d %n", port);
// wait for and then accept client connection
// a socket is created to handle the created connection
Socket clientSocket = serverSocket.accept();
System.out.printf("Connected to client %s on port %d %n",
clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort());
// Create stream to receive data from client
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response);
/////////////////////////////////////////////
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); // he doesn't reach here
System.out.println("here-serv");
System.out.println(clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
// Send text to server as bytes
out.writeBytes("echo");
I actually believe this problem has something with the readline from server, it is not getting a null - but the client sends a "\n"! Can you find my code mistake? Thanks
I'm trying to implement a little communication scheme handling HTTP-requests from an Android device to a Node.js server. With the current code the Android side closes the connection after receiving the response from the header.
Java:
public String doInBackground(Void... params) {
URL url = new URL("http://" + mServer.getHost() + ":" + mServer.getPort() + "/" + mPath);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(TIMEOUT);
http.setRequestMethod("POST");
http.setDoOutput(true);
http.connect();
OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(mJson);
writer.flush();
writer.close();
mResponseCode = http.getResponseCode();
if (mResponseCode != 200) {
http.disconnect();
return "";
}
InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);
char[] chars = new char[BUF_SIZE];
int size = br.read(chars);
String response = new String(chars).substring(0, size);
//http.disconnect();
return response;
}
Node:
this.socket = http.createServer((req, res) => {
req.on('data', (chunk) => {
this.log.info("DATA");
obj = JSON.parse(chunk.toString());
});
req.on('close', () => {
this.log.info("CLOSE");
});
req.on('connection', (socket) => {
this.log.info("CONNECTION");
});
req.on('end', () => {
this.log.info("END");
});
});
this.socket.listen(this.port, this.host);
Further the connection event on the Node side is never called, every request is directly piped into the data event.
Is there a way to establish a persistent HTTP-connection such that the Node server can keep track of it while the connection is running until the Android side closes it again?
Socket.io seems to be a reasonable library to achieve persistent connections from Android to a Node.js server.
I have to connect with a server (I donĀ“t have access to the server code) but the transmission protocol (Socket) is:
(client) --> data
ack <-- (server)
data response <-- (server)
(client) --> ack
It's assumed that the server should always respond quickly. I connect to the server, I send the data but the response is NULL and if I debug my code, an exception occurs when I catch the response:
"java.net.SocketException: Software caused connection abort: recv failed"
My code:
public static void main(String[] args){
try{
String order = "datahere";
String responseServer;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(order);
responseServer = inFromServer.readLine();//exception if I try to debug my code
System.out.println("From server: " + responseServer); //responseServer is NULL
clientSocket.close();
} catch (IOException ex) {
System.out.println("Error: "+ex);
}
}
That's wrong? Any idea?
I tried to disable the firewall and also add a rule for the port 9300 but the result is the same.
The client gave me an example code in Vb.Net that it's supposed to work and I try to replicate it in Java.
Code in Vb.Net:
Dim message As String = "datahere";
Try
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
Dim client As New TcpClient(ip, port)
Dim stream As NetworkStream = client.GetStream()
stream.Write(data, 0, data.Length)
data = New [Byte](2048) {}
Dim responseData As [String] = [String].Empty
Dim bytes As Integer = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
stream.Close()
client.Close()
Catch ex As Exception
End Try
SOLUTION:
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
clientSocket.getOutputStream().write(order.getBytes("ASCII"));
byte[] data = new byte[2048];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);
//Another way to catch the response:
//InputStreamReader in = new InputStreamReader(clientSocket.getInputStream());
//int data1 = in.read();
//while(data1 != -1) {
// System.out.print((char) data1);
// data1 = in.read();
//}
clientSocket.close();
Here is a translation of your VB code in java
public static void main(String[] args) throws IOException {
String order = "datahere";
// Try-with-resource statement will close your socket automatically
try (Socket clientSocket = new Socket("XXX.XX.XX.XX", 9300)) {
// Send to the sever the order encoded in ASCII
clientSocket.getOutputStream().write(order.getBytes("ASCII"));
// Sleep until we have bytes to read available
while (clientSocket.getInputStream().available() == 0) {
Thread.sleep(100L);
}
// Create the buffer of exactly the amount of bytes available without blocking
byte[] data = new byte[clientSocket.getInputStream().available()];
// Read the bytes from the server and put it into the buffer
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
// Decode what has been read from the server that was encoded in ASCII
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);
}
}
DataInputStream dis = new DataInputStream( new InputStreamReader(clientSocket.getInputStream()));
while(dis.available()>0){
//reads characters encoded with modified UTF-8
String temp = dis.readUTF();
System.out.print(temp+" ");
}
try to use a dataInputStream instead of bufferedReader and use readUTF() method in dataInputStream to read UTF characters.
I'm trying to send a TCP packet. It sends correctly to the server but sender is not getting response (server is sending response back correctly). Client doesn't even process code afeter sending the packet...
Socket socket = new Socket (ip, port);
PrintWriter mOut = new PrintWriter(socket.getOutputStream(), true);
mOut.print("DSPSYSSTS");
//Everything works fine until here
BufferedReader mIn = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
String fromClient = mIn.readLine();
out.println ("Client Message: " + fromClient);
mOut.close();
mIn.close ();
socket.close ();
The JSP doesn't print the input and it remains loading forever. What's wrong?
Returning String of systemRequest.request in below code
ReadSpoolFile readSplf = new ReadSpoolFile(splfArray.get(0));
String splfContent = readSplf.read();
GetSystemStatus getSysSts = new GetSystemStatus();
String systemStatus = getSysSts.get(splfContent);
return systemStatus + "\r\n";
Server side Response:
String response = systemRequests.request(message, SystemRequests.SILENT_OFF);
ChannelBuffer mCbResponse;
if(response != null){
mCbResponse = ChannelBuffers.copiedBuffer(response.getBytes());
mChannel.write(mCbResponse); //<------Write response
Try this:
mOut.print("DSPSYSSTS");
mOut.flush();
...