Android Socket connection to bitcoin node - java

I can't get a response from a bitcoin node using a simple java socket on android. I send a version message and wait for a response, but nothing is returned. The code is fairly simple:
private void connect(Peer peer) {
Log.i(App.TAG, "connect to: " + peer.ip + ":8333");
InetSocketAddress address = new InetSocketAddress(peer.ip, 8333);
Socket socket = new Socket();
try {
socket.connect(address, 10000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
VersionMessage versionMessage = new VersionMessage();
writeMessage(versionMessage, out);
readMessage(in);
Log.i(App.TAG, "Shutting down....");
out.close();
in.close();
socket.close();
} catch (IOException e) {
Log.i(App.TAG, "Socket failed to conenct");
}
}
private void writeMessage(BaseMessage message, OutputStream out) {
Log.i(App.TAG, "writeMessage: " + message.getCommandName());
byte[] header = message.getHeader();
byte[] payload = message.getPayload();
try {
Log.i(App.TAG, "header: " + Util.bytesToHexString(header));
Log.i(App.TAG, "payload: " + Util.bytesToHexString(payload));
out.write(header);
out.write(payload);
} catch (IOException e) {
Log.i(App.TAG, "Failed to write message");
}
}
private void readMessage(InputStream in) throws IOException {
Log.i(App.TAG, "readMessage");
while (true) {
int b = in.read();
Log.i(App.TAG, "read: " + b);
if (b == -1) {
Log.i(App.TAG, "END OF CONNECTION!");
break;
}
response.add(b);
}
}
The logs from the app are as follows:
connect to: 52.88.14.46:8333
writeMessage: version
header: f9beb4d976657273696f6e00000000006100000061000000
payload: 7c9c000001000000000000005a73788200000000524543495049454e54204950000000000000000000000000000053454e44455220495000000000000000000000000000000000006237646465346163626f657463686169000000000000000000
readMessage
read: -1
END OF CONNECTION!
Shutting down....
Here is a link to the project: https://github.com/boetchain/android-bitcoin-node

The checkSum field is mandatory and fellow nodes will just ignore incoming messages without a valid checksum.

Related

Open Source Java HTTP Codecs

I am writing a web server from the scratch. There I need a Http codec which can decode a string request (buffer) to an Http object and encode http object into Sting (buffer).
I found three Codecs,
Apache Codecs (can't use this because this is tightly coupled with their server coding structure)
Netty Codes (can't use this because this is tightly coupled with their server coding structure)
JDrupes Codecs (Has some concurrency issues)
But non of these can be used for my purpose. Are there any other Codecs I can use?
class SimpleHttpsServer implements Runnable {
Thread process = new Thread(this);
private static int port = 3030;
private String returnMessage;
private ServerSocket ssocket;
/************************************************************************************/
SimpleHttpsServer() {
try {
ssocket = new ServerSocket(port);
System.out.println("port " + port + " Opend");
process.start();
} catch (IOException e) {
System.out.println("port " + port + " not opened due to " + e);
System.exit(1);
}
}
/**********************************************************************************/
public void run() {
if (ssocket == null)
return;
while (true) {
Socket csocket = null;
try {
csocket = ssocket.accept();
System.out.println("New Connection accepted");
} catch (IOException e) {
System.out.println("Accept failed: " + port + ", " + e);
System.exit(1);
}
try {
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(csocket.getInputStream()));
PrintStream printStream = new PrintStream(new BufferedOutputStream(csocket.getOutputStream(), 1024),
false);
this.returnMessage = "";
InputStream inputStream = csocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// code to read and print headers
String headerLine = null;
while ((headerLine = bufferedReader.readLine()).length() != 0) {
System.out.println(headerLine);
}
// code to read the post payload data
StringBuilder payload = new StringBuilder();
while (bufferedReader.ready()) {
payload.append((char) bufferedReader.read());
}
System.out.println("payload.toString().length() " + payload.toString().length());
if (payload.toString().length() != 1 || payload.toString().length() != 0) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(payload.toString());
// Handle here your string data and make responce
// returnMessage this can store your responce message
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + this.returnMessage;
printStream.write(httpResponse.getBytes("UTF-8"));
printStream.flush();
}else {
/*String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
outStream.write(httpResponse.getBytes("UTF-8"));
outStream.flush();*/
}
printStream.close();
dataInputStream.close();
// csocket.close();
System.out.println("client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/************************************************************************************/
public static void main(String[] args) {
new SimpleHttpsServer();
}
}
may be this one is help you

How to read or print the BufferedReader ( InputStreamReader)

I´m creating a new socket to send a string through the socket, then the socket generates a reply (I monitor the reply in Wireshark) but in the code I cannot see any answer, only if I connect again to the socket with another app, then I receive the answer in the first socket connection.
public class TCPConnections
{
public static void main (String[] args) throws Exception
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
String response = "";
String hostGreetings = "<frame><cmd><id>5</id><hostGreetings><readerType>SIMATIC_RF680R</readerType><supportedVersions><version>V2.0</version></supportedVersions></hostGreetings></cmd></frame>\n";
String getReaderStatus = "<frame><cmd><id>2</id><getReaderStatus></getReaderStatus></cmd></frame>\n";
StringBuilder antwort = new StringBuilder();
int c;
int counter = 0;
try
{
String host = "30S50RFID01.w30.bmwgroup.net";
int port = 10001;
InetAddress address = InetAddress.getByName(host);
System.out.println("adress: " + address);
socket = new Socket(address, port);
System.out.println("Socket connected: " + socket.isConnected());
System.out.println("Remote Port: " + socket.getPort());
System.out.println("Traffic Class: " + socket.getTrafficClass());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//byte [] bytes = hostGreetings.getBytes("UTF-8");
//System.out.println("UTF-8 = "+bytes);
if (socket.isConnected())
{
out.println(hostGreetings);
System.out.println("Message send:" + hostGreetings);
System.out.println("Message send:" + socket.getOutputStream());
System.out.println("Greeting sent, waiting for response");
Thread.sleep( 2000 );
boolean reading = true;
while (reading) {
if(in.ready ()){
c = (char) in.read();
response = response + c;
System.out.println("Reply" + response);
}else {
reading = false;
}
}
}
}
else
{
System.out.println("Socket connected: " + socket.isConnected());
}
}
catch (IOException ex)
{
System.out.println("Error 1: " + ex.getMessage());
}
catch (InterruptedException ex)
{
Logger.getLogger(TCPConnections.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{//Closing the socket
try
{
System.out.println("Connection will be closed and program terminated");
out.close();
in.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("Error 2: " + ex.getMessage());
}
}
}
}`

TCP Sockets Client/Server - server only respondsto first connection from client

I have some simple client and server code, where the client sends some bytes to the server, and the server responds with some bytes. The client prints the received bytes, and then closes the socket.
This works fine the first time the client runs, but subsequent calls get no response.
package sockets.com;
// Client Side
import java.io.*;
import java.net.*;
public class ClientSideTCPSocket {
public void run() {
try {
int serverPort = 4023;
InetAddress host = InetAddress.getByName("localhost");
System.out.println("Connecting to server on port " + serverPort);
Socket socket = new Socket(host, serverPort);
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
String s = "HELLO SERVER";
byte[] bytes = s.getBytes("US-ASCII");
for (byte b : bytes) {
out.write(b);
}
int ch = 0;
while ((ch = in.read()) >= 0) {
System.out.println("Got byte " + ch);
}
out.flush();
out.close();
socket.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ClientSideTCPSocket client = new ClientSideTCPSocket();
client.run();
}
}
Server code
package sockets.com;
//Server Side
import java.net.*;
import java.io.*;
public class ServerSideTCPSocket {
public void run() {
try {
int serverPort = 4023;
ServerSocket serverSocket = new ServerSocket(serverPort);
serverSocket.setSoTimeout(900000);
while (true) {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
//
int ch = 0;
while ((ch = server.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
}
// Write to output stream
OutputStream out = server.getOutputStream();
String s = "HELLO CLIENT";
byte[] bytes = s.getBytes("US-ASCII");
for (byte b : bytes) {
System.out.println(b);
out.write(b);
}
}
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSideTCPSocket srv = new ServerSideTCPSocket();
srv.run();
}
}
Would be grateful for any comments regarding why this is the case. Thank you.
A few things:
This block of code will loop forever until after the client closes his connection:
while ((ch = server.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
}
Then after the client closes his connection, the subsequent attempt to send "HELLO CLIENT" to the socket will generate an IO exception. That will trigger your server loop to exit.
The easy fix is to adjust your protocol such that the "message" is completed on some sentinel char. In my easy fix, I just adjusted it to break out when a ! was received.
Better to have each client session terminate on an ioexception instead of the entire server block. My refactor of your code:
public class ServerSideTCPSocket {
public void tryCloseSocketConnection(Socket socket) {
try {
socket.close();
}
catch(java.io.IOException ex) {
}
}
public void processClientConnection (Socket clientConnection) throws java.io.IOException {
int ch = 0;
while ((ch = clientConnection.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
if (ch == '!') {
break;
}
}
// Write to output stream
OutputStream out = clientConnection.getOutputStream();
String s = "HELLO CLIENT!";
byte[] bytes = s.getBytes("US-ASCII");
for (byte b : bytes) {
System.out.println(b);
out.write(b);
}
}
public void run() {
try {
int serverPort = 4023;
ServerSocket serverSocket = new ServerSocket(serverPort);
serverSocket.setSoTimeout(900000);
while (true) {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket clientConnection = serverSocket.accept();
try {
System.out.println("Just connected to " + clientConnection.getRemoteSocketAddress());
processClientConnection(clientConnection);
}
catch (java.io.IOException ex) {
System.out.println("Socket connection error - terminating connection");
}
finally {
tryCloseSocketConnection(clientConnection);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSideTCPSocket srv = new ServerSideTCPSocket();
srv.run();
}
}
Then adjust your client code's message to be:
String s = "HELLO SERVER!"; // the exclamation point indicates "end of message".

rtsp client code not working

I am facing problem in Java socket communication, I am running Live555 Media Server and one small app (some what similar to proxy server code, referred one online code snippet) in one machine, and also created one client code and running in my laptop. All machines are in same network. When I send RTSP Command from client to proxy, It is receiving properly and it is redirecting that received command to Live555 server and its getting back proper response but the response is not receiving in client. Help me to fix this problem and also suggest me some doc link to understand the problem.
here is my proxy code,
public class TestProxyServer {
public static void main(String[] args) {
try {
String host = "127.0.0.1";
int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting proxy for " + host + ":" + serverPort
+ " on port " + proxyPort);
runServer(host, serverPort, proxyPort);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sProt, int pPort) throws IOException {
ServerSocket ss = new ServerSocket(pPort);
final byte[] request = new byte[1024];
byte[] replay = new byte[1024];
while(true) {
Socket server = null, client = null;
try {
client = ss.accept();
final InputStream fromClient = client.getInputStream();
final OutputStream toClient = client.getOutputStream();
// for Live555
try {
server = new Socket(host, sProt);
} catch(Exception e) {
PrintWriter out = new PrintWriter(toClient);
out.print("Proxy can not connect to Live555 on host " + host + " with the port " + sProt + "\n");
out.flush();
client.close();
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String ClientMSG;
while((bytesRead = fromClient.read(request)) != -1) {
toServer.write(request, 0, bytesRead);
ClientMSG = new String(request, 0, bytesRead);
System.err.println("From Client : " + ClientMSG);
toServer.flush();
}
} catch(Exception e) {
try {toServer.close();} catch(IOException ioe){}
}
}
};
t.start();
int bytesRead;
try {
String toCMSG;
while((bytesRead = fromServer.read(replay)) != -1) {
toClient.write(replay, 0, bytesRead);
toCMSG = new String(replay, 0, bytesRead);
System.err.println("Response from Live555 " + toCMSG);
toClient.flush();
}
} catch(Exception e) {
toClient.close();
// e.printStackTrace();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(server != null)
server.close();
if(client != null)
client.close();
}
}
}
}
and client code is here,
public class Test {
public static void main(String[] args) {
try {
String host = "192.168.1.9";
// int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting Client to connect proxy on " + host + ":" + " with port " + proxyPort);
runServer(host, proxyPort);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sPort) throws IOException {
final byte[] request = new byte[1024];
final byte[] reply = new byte[1024];
while (true) {
Socket server = null;
try {
// for Proxy
try {
server = new Socket(host, sPort);
} catch (Exception e) {
System.out.println("Proxy can not connect to ProxyServer on host " + host + " with the port " + sPort + "\n");
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
int bytesRead;
try {
String RtspMSG = "DESCRIBE rtsp://192.168.1.9:8554/free.ts RTSP/1.0\r\nCSeq: 2\r\n\r\n";
// while((bytesRead = fromClient.read(RtspMSG.getBytes()))
// != -1) {
toServer.write(RtspMSG.getBytes(), 0, RtspMSG.length());
System.err.println("Sent : " + RtspMSG);
toServer.flush();
// }
} catch (Exception e) {
try {
toServer.close();
} catch (IOException ioe) {
}
}
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String response = null;
System.err.println("----------------------------------");
while ((bytesRead = fromServer.read(reply)) != -1) {
response = new String(reply, 0, bytesRead);
}
System.err.println("Response from Proxy : "
+ response);
} catch (Exception e) {
try {
fromServer.close();
} catch (Exception e1) {
}
// e.printStackTrace();
}
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (server != null)
server.close();
}
}
}
}
Thank You

IllegalBlockingModeException using sockets

I'm trying to write a chat server and client that uses sockets. Connecting the client works properly and I get the correct output from the server:
Listening on port 8000
Got connection from Socket[addr=/127.0.0.1,port=50628,localport=8000]
But when I send something from the client I get IllegalBlockingModeException. Here's what I have:
public void listen()
{
try {
// Open a non-blocking socket channel
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
// Get the socket and bind it
ServerSocket ss = ssc.socket();
InetSocketAddress isa = new InetSocketAddress(this.getServerName(), this.getServerPort());
ss.bind(isa);
// Create the selector
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Listening on port " + this.getServerPort());
while (true)
{
// Wait for at least one channel to be selected
if (selector.select() == 0)
continue;
// Iterate the key set and dispatch messages
Set keys = selector.selectedKeys();
Iterator it = keys.iterator();
while (it.hasNext())
{
SelectionKey key = (SelectionKey)it.next();
if (key.isAcceptable()) {
Socket s = ss.accept();
System.out.println("Got connection from " + s);
SocketChannel sc = s.getChannel();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
else if (key.isReadable()) {
SocketChannel sc = null;
try {
sc = (SocketChannel)key.channel();
String message = processInput(sc);
if (message == null) {
key.cancel();
Socket s = null;
try {
s = sc.socket();
System.out.println("Closing connection to " +s);
s.close();
} catch( IOException ie ) {
System.err.println("Error closing socket " + s + ": " + ie);
}
}
else {
String response = getListener().process(sc, message);
ObjectOutputStream oos = new ObjectOutputStream(Channels.newOutputStream(sc));
//ObjectOutputStream oos = new ObjectOutputStream(sc.socket().getOutputStream());
oos.writeObject(response + "\n");
oos.close();
}
}
catch(IOException ie) {
key.cancel();
try {
sc.close();
} catch(IOException ie2) {
System.out.println(ie2);
}
System.out.println("Closed " + sc);
}
}
}
keys.clear();
}
}
catch (IOException ex) {
System.out.println(ex);
System.exit(1);
}
}
private String processInput( SocketChannel sc ) throws IOException {
buffer.clear();
sc.read( buffer );
buffer.flip();
if (buffer.limit()==0) {
return null;
}
return decoder.decode(buffer).toString();
}
Here's the stack trace:
java.nio.channels.SocketChannel[connected local=/127.0.0.1:8000 remote=/127.0.0.1:50656]
Exception in thread "main" java.nio.channels.IllegalBlockingModeException
at java.nio.channels.Channels.writeFully(Channels.java:97)
at java.nio.channels.Channels.access$000(Channels.java:61)
at java.nio.channels.Channels$1.write(Channels.java:174)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1870)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1779)
at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:247)
at ChatServer$Server.listen(ChatServer.java:171)
at ChatServer.run(ChatServer.java:231)
at ChatServer.main(ChatServer.java:247)
Java Result: 1
Does anybody know how to solve this?
You can't use Channels.newXXXStream() on a channel in non-blocking mode. See the Javadoc.
Ok, I managed to put it to work. Here's how:
String response = getListener().process(sc, message) + "\n";
ByteBuffer bb = ByteBuffer.wrap(response.getBytes("utf-8"));
sc.write(bb);
Instead of using an OutputStream, write directly to the SocketChannel.

Categories

Resources