Is this even possible? I have a java server program on a mac that I need to use to communicate back to a windows program. I have the client working in Java, but I can't seem to figure out how to get it to work in VB.net...
Here is the Java code...
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class socketClient {
public static void main(String[] args) {
/**
* Define a host server
*/
String host = "10.1.1.194";
/**
* Define a port
*/
int port = 19999;
StringBuffer instr = new StringBuffer();
String TimeStamp;
System.out.println("SocketClient initialized");
try {
//Obtain an address object of the server
InetAddress address = InetAddress.getByName(host);
//Establish a socket connection
Socket connection = new Socket(address, port);
//Instantiate a BufferedOutputStream object
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
/**
* Instantiate an OutputStreamWriter object with the optional
* character encoding.
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
TimeStamp = new java.util.Date().toString();
String process = "Initiate file transfer on " + host + " port " + port
+ " at " + TimeStamp + (char) 13;
//Write across the socket connection and flush the buffer
osw.write(process);
osw.flush();
/**
* Instantiate a BufferedInputStream object for reading /**
* Instantiate a BufferedInputStream object for reading incoming
* socket streams.
*/
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
/**
* Instantiate an InputStreamReader with the optional character
* encoding.
*/
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
//Read the socket's InputStream and append to a StringBuffer
int c;
while ((c = isr.read()) != 13) {
instr.append((char) c);
}
//Close the socket connection.
connection.close();
System.out.println(instr);
}
catch (IOException f)
{
System.out.println("IOException: " + f);
}
catch (Exception g)
{
System.out.println("Exception: " + g);
}
}
}
And here is my VB.NET code that I have so far...
Private clientSocket As Socket
Private host As String = "10.1.1.194"
Private port As Integer = 19999
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
Dim add As New IPEndPoint(IPAddress.Parse(host), port)
clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
clientSocket.Connect(add)
Dim netStream As New NetworkStream(clientSocket, True)
Dim outstream As Byte() = System.Text.Encoding.ASCII.GetBytes("Initiate file transfer from " _
& System.Environment.MachineName & " on " & host & " port " & port & " at " & TimeOfDay)
netStream.Write(outstream, 0, outstream.Length)
netStream.Flush()
Catch ex As Exception
Debug.Write(ex.Message)
End Try
End Sub
Now, if I run the vb code, it hangs... and nothing appears in my console on the mac (Like it does when I use the java client), however, when I close the VB code, I get the java.net.SocketException: Connection reset error, so I must be getting pretty close to figuring this out.
The thing is, I know almost nothing when it comes to socket programming, so if someone could push me in the right direction, it would be very appreciated!
Is this even possible?
Yes.
I don't see you writing Carriage Return (13) character anywhere in your VB.NET example, yet you expect it to appear on a Java side in order to print something to the console.
Related
I have connection to TCP server (ip,port) to which meter is connected. I'd like to read the specified data from this port because when I'm using standard read method it sends me the whole data stream which takes about 15 minutes to read. So my question: is there any method I can use to get one specified register's value using his OBIS code (1.1.1.8.0.255 - active energy taken) in java via TCP server?
import java.net.*;
import java.io.*;
public class scratch {
public static void main(String[] args) {
String hostname = "ip (hidden)";
int port = port (hidden);
try (Socket socket = new Socket(hostname, port)) {
OutputStream out = socket.getOutputStream();
InputStream input = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int character;
StringBuilder data = new StringBuilder();
String test = "/?!\r\n";
byte[] req = test.getBytes();
out.write(req);
while ((character = reader.read()) != '\n') {
data.append((char) character);
}
System.out.println(data);
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
The message "test" send initiation request to meter and his respond is correct but I dont' know how to put flags (ACK STX ETX) in my request, I've tried something like this:
String test2 = (char)0x6 + "051\r\n";
byte[] req2 = test2.getBytes("ASCII");
out.write(req2);
But meter doesn't recognize it.
I am making an HTTP server and HTTP web client for simple Http request and response.
This is the code for Server
import java.io.*;
import java.net.*;
import java.util.*;
public final class WebServer{
public static void main(String[] args) throws Exception{
//storing port number
int port = 2048;
//open socket and wait for TCP connection
ServerSocket serverConnect = new ServerSocket(port);
System.out.println("Server started.\nListening for connections on port : " + port + " ...\n");
// we listen until user halts server execution
while (true) {
//Construct an object to process the HTTP request message.
//This will call another class where we do everything else
HttpRequest request = new HttpRequest(serverConnect.accept());
//create a new thread to process the request
Thread thread = new Thread(request);
thread.start();
} //end of while
}//end of main
}//end of the class webServer
The code for HttpRequest class is as follow:
import java.io.*;
import java.net.*;
import java.util.*;
final class HttpRequest implements Runnable{
final static String CRLF = "\r\n";
Socket socket;
//start of constructor
public HttpRequest(Socket socket) throws Exception{
this.socket=socket;
}//end of constructor
//Implement the run() method of the Runnable interface.
public void run(){
try{
processRequest();
}
catch(Exception e){
System.out.println(e);
}
}//end of run
private void processRequest() throws Exception{
//Get a reference to the scoket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
//set up the stream filters
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Get the request line of the HTTP request message.
String requestLine = br.readLine();
//Display the request line
System.out.println();
System.out.println(requestLine);
//Get and display the header lines.
String headerLine = null;
while((headerLine = br.readLine()).length()!=0){
System.out.println(headerLine);
}
//System.out.println(requestLine);
//Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); //skip over the method, which should be. "GET"
String fileName = tokens.nextToken();
//Prepend a "." so that file request is within the current directory
fileName = "." + fileName;
//printing for test
//System.out.println(fileName);
//Open the requested file
FileInputStream fis = null;
boolean fileExists = true;
try{
fis = new FileInputStream(fileName);
}
catch(FileNotFoundException e){
fileExists = false;
}
//Construct the response message
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if(fileExists){
statusLine = tokens.nextToken();
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
}
else{
statusLine = "HTTP/1.1 404 File Not Found";
contentTypeLine = "Content-type: " + "text/html" + CRLF;
entityBody = "<html><head><title>Not Found </title></head>" +
"<BODY>Not Found</body></html>";
}
//send the status line
os.writeBytes(statusLine);
//send the content Type
os.writeBytes(contentTypeLine);
//send a blank line to indicate the end of the header lines
os.writeBytes(CRLF);
//send the entity Body
if(fileExists){
sendBytes(fis, os);
fis.close();
}
else{
os.writeBytes(entityBody);
os.writeBytes(CRLF);
}
//Close scokets and streams.
fis.close();
os.close();
br.close();
socket.close();
}//end of processRequest
private static String contentType(String fileName){
if(fileName.endsWith(".htm") || fileName.endsWith(".html")){
return "text/html";
}
if(fileName.endsWith(".gif")){
return "image/gif";
}
if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")){
return "image/jpeg";
}
return "application/octet-stream";
}// end of contentType
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception{
//Construct a 1k buffer to hold bytes on their way to the Socket
byte[] buffer = new byte[1024];
int bytes = 0;
//Copy requested file into the scoket's output stream.
while((bytes = fis.read(buffer)) != -1){
os.write(buffer, 0, bytes);
}//end of while
}//end of sendBytes
} // end of the class
The Code works fine when I make a request from Chrome webbrowser. However, I made WebClient as well. When I make request from WebClient, I am stuck as the program runs forever.
As far I have tracked, the pointer does not move from the br.readline on the while loops on the Server Side.
The code for my client is as follow.
import java.io.*;
import java.net.*;
import java.util.*;
public class WebClient{
final static String CRLF = "\r\n";
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
// System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("GET /" +args[2] +" HTTP/1.1");
out.writeUTF(CRLF);
out.writeUTF("Host: "+client.getLocalSocketAddress());
out.writeUTF(CRLF);
out.writeUTF("Connection: close" + CRLF);
out.writeUTF("User-agent: close" + CRLF);
out.writeUTF(CRLF);
//Cache-Control: max-age=0
System.out.println("Just connected to 1 ");
InputStream inFromServer = client.getInputStream();
System.out.println("Just connected to 2 ");
BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer));
System.out.println("Just connected to 3 ");
String headerLine = null;
while((headerLine = br.readLine()).length()!=0){
System.out.println("asd"+headerLine);
}
System.out.println("Just connected to 4 ");
client.close();
System.out.println("Just connected to 5 ");
} catch (IOException e) {
e.printStackTrace();
}
}
}//end of the class WebClient
Can anyone help me figure out the problem.
Thanks.
First of all, you have to remove line fis.close(); (right before os.close();) in your HttpRequest class: if no file exists, this line raises NullPointerException because fis is null, so after sending Not Found response to the browser, your server does not close the socket accepted from that browser, that's why even though you see Not Found in your browser, your request never ends.
Secondly, the reason of why your client gets stuck is writeUTF() method that you used for sending request header. Seems that this line out.writeUTF(CRLF); does not really send an empty string but adds some other UTF-related character(s) (you may notice that in your server's console output), so your server gets stuck at while((headerLine = br.readLine()).length()!=0) waiting for the client to send an empty string, but never receives it. You need to replace out.writeUTF(CRLF); with out.writeBytes(CRLF);.
Also, it makes little sense to use BufferedReader for receiving binary files from socket. Reader in general is used with character-input stream, so it is not applicable for your case. You may use InputStream instead, by replacing this fragment:
String headerLine = null;
while((headerLine = br.readLine()).length()!=0){
System.out.println("asd"+headerLine);
}
with this (I chose buffer size of 4096, you may replace it with your preferred value):
int readBytes;
byte[] cbuf = new byte[4096];
while((readBytes=inFromServer.read(cbuf, 0, 4096))>-1){
System.out.println("read: " + readBytes);
}
Note: You may easily notice here that InputStream.read() will fetch not only the file itself but also statusLine, contentTypeLine and two CRLFs, so in case if you would like to separate them from the file, you may read them first, by issuing two "readLines" and then fetch the file only by read()
In your server, you use writeBytes()
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. If no exception is thrown, the counter written is incremented by the length of s.
While you may worry about non-ASCII text, generally this is what you need.
In your client you attempt to use writeUTF()
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
While that 2-byte length in the beginning can be useful in other cases, it is not what web servers expect, including yours (and that is correct). So use writeBytes() everywhere in your client, and it will suddenly work:
out.writeBytes("GET /" +args[2] +" HTTP/1.1");
out.writeBytes(CRLF);
out.writeBytes("Host: "+client.getLocalSocketAddress());
out.writeBytes(CRLF);
out.writeBytes("Connection: close" + CRLF);
out.writeBytes("User-agent: close" + CRLF);
out.writeBytes(CRLF);
In fact those extra bytes may be visible in your server output, at least when I ran it in Eclipse, I saw garbage characters, as a combination of mysterious empty space and a tiny question mark in a rectangle (note how they also appear at the end of the lines when CRLF is sent separately):
(The first request is the one issued with writeUTF, and the second one comes from Chrome)
This is not a possible duplicate. No answer on this site adequately answers or solves my issue.
I am trying to connect to a VB.NET server via TCP socket and get response in Android application. The response is always null as string or -1 as bytes.
I have to connect and get a response for multiple platforms but for the moment I just want to focus on the Android app. Maybe if I figure it out, it will be easier to move forward to other platforms.
I do not have access to edit any code in the VB.NET live server. There system is pretty old and has been only sending responses to other Windows clients up until now.
Here is my Android client. It is inside a background task which is called from the mainActivity. The below command string should return coordinates in the form of a string from the server. Nothing is returned.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void sendMessage() throws IOException, InterruptedException {
Socket socket = null;
String host = "";
int port = ;
PrintStream stream = null;
String command="";
try {
Socket s = new Socket(host,port);
System.out.println("Socket created");
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(command);
output.flush();
System.out.println("command sent");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
System.out.println("Getting response:");
String st = input.readLine();
System.out.println("Response : " + st);
//Close connection
s.close();
}
catch (UnknownHostException e) {
System.out.println("Don't know about host : " + host);
e.printStackTrace();
System.exit(1);
}
catch (IOException e) {
System.out.println("Couldn't get I/O for the connection to : " + host);
e.printStackTrace();
System.exit(1);
}
}
}
A developer also sent me a test client in VB which connects, sends and recieves without problem
Here is a class of a VB:NET Dummy server project the developer has sent me to see how the live server is setup code-wise. I can see it gets the string as unicode but I am not confident in VB to know where my Java code is going wrong.
When I open the project and start the server on localhost I cant connect to it from the java client anyway. Then I have written another client in PHP, same problem, connection established but no response. I downloaded a socket tester software but it also can connect but does not get a response.
Option Explicit On
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic
Imports System.Net.Dns
Imports System.Text.UnicodeEncoding
Imports System.Threading
Imports System.Data.SqlClient
Public Enum glenConnectionType
ConstantConnection = 1
ConnectOnDemand = 2
AsyncConnection = 3
End Enum
Public Class clsDynaListner
Public tcpServer As Socket
Public tcpClient As Socket
Public tcpPort As Integer
Public tcpBilnr As Integer ' was shared SHOULD PROB BE INITIALISED TO 0
Public ThreadClient As Thread
Public LastKontakt As Date = Nothing
Public ConActive As Boolean = False
Private tcpClientEndPoint As System.Net.IPEndPoint
Private bCommandLength(15), bReplyLength(15) As Byte
Private iCommandLength, iReplyLength As Integer
Private sReplyLength As String
Private sCommand, sReply As String
Private theCommandBytes() As Byte
Private theReplyBytes() As Byte
Private Const AsyncMaxBytes As Integer = 600000 '1024
Public Shared AsyncData As String = Nothing
Public Sub New(ByVal currentTCPPort As Integer, ByVal theConnectionType As glenConnectionType)
tcpPort = currentTCPPort
tcpClientEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, tcpPort)
'Select Case theConnectionType
' Case glenConnectionType.ConstantConnection
' ThreadClient = New Threading.Thread(AddressOf ListenForConstantConnection)
' Case glenConnectionType.ConnectOnDemand
ThreadClient = New Threading.Thread(AddressOf ListenForConnectOnDemand)
' Case glenConnectionType.AsyncConnection
'ThreadClient = New Threading.Thread(AddressOf ListenForAsyncConnection)
'End Select
ThreadClient.Start()
End Sub
Private Sub ListenForConnectOnDemand()
While (True)
Try
tcpServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
tcpServer.SendBufferSize = TCP_BUFFER_SIZE
tcpServer.ReceiveBufferSize = TCP_BUFFER_SIZE
tcpServer.Blocking = True
tcpServer.Bind(tcpClientEndPoint)
tcpServer.Listen(0)
tcpClient = tcpServer.Accept
tcpClient.SendBufferSize = TCP_BUFFER_SIZE
tcpClient.ReceiveBufferSize = TCP_BUFFER_SIZE
' Find out how big the command is going to be
tcpClient.Receive(bCommandLength)
iCommandLength = CType(Unicode.GetString(bCommandLength), Integer)
' Bring that command to daddy
Array.Resize(theCommandBytes, iCommandLength + 1)
tcpClient.Receive(theCommandBytes)
sCommand = Unicode.GetString(theCommandBytes)
gInMessage = sCommand
' Get the reply
sReply = "Response:"
gOutMessage = sReply
' Inform the controller of the length of the reply transmission
iReplyLength = (sReply.Length * 2) - 1
sReplyLength = iReplyLength.ToString.PadLeft(8, "0")
bReplyLength = Unicode.GetBytes(sReplyLength)
tcpClient.Send(bReplyLength)
' Send the reply data
Array.Resize(theReplyBytes, iReplyLength + 1)
theReplyBytes = Unicode.GetBytes(sReply)
tcpClient.Send(theReplyBytes)
Array.Clear(theCommandBytes, 0, theCommandBytes.Length)
Array.Clear(theReplyBytes, 0, theReplyBytes.Length)
tcpClient.Close()
tcpServer.Close()
tcpClient = Nothing
tcpServer = Nothing
Catch ex1 As Exception
Try
tcpClient.Close()
tcpServer.Close()
tcpClient = Nothing
tcpServer = Nothing
' ErrMessage = "LisForContr :" & tcpPort.ToString & ex1.Message
Catch
End Try
End Try
End While
End Sub
Protected Overrides Sub Finalize()
Try
tcpServer.Close()
ThreadClient.Abort()
Catch
End Try
MyBase.Finalize()
End Sub
End Class
I have been working with this for a while. The apps I have built are complete for PHP Web App, Android Native, and iPhone Native. The problem is only getting the response from the VB server.
Would like some help to push me in the right direction.
Also I enquired with the developers if the response has a line-break. It does not and it does seem they are willing to mess with the code as it served there purpose for many many years. So I have to find away around that.
If you need me to provide more info just ask.
To send to a VB.NET server from Java you must send the string as unicoded bytes. Send the length at the bytes to expect first and then send the primary data and flush. You have to know exactly what the server is expecting in order to format and encode the data accordingly in preparation to send it.
I was able to successfully fix my issue after debugging VB client and server. This client will process byte arrays, stream advanced sql commands and get the response. The update will be getting xml table data. Anyone who wants to input how to make this client better. You are welcome.
Updated my java client as follows.
/**
* MR-TCP Java & VB.NET DataExchange Client 0.95 - Maze Runner 2015
*/
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static String sendCommand(String commandString, Boolean IsID) throws IOException, InterruptedException {
String host;
int port;
String command;
byte[] commandBytes;
String commandLength;
byte[] cmdLengthBytes;
Socket s;
DataOutputStream stream;
String dataString = "";
host = ""; //
port = 0; //
command = commandString;
commandBytes = command.getBytes("UTF-16LE"); // returns byte[18]
if(IsID){
commandLength = "00000021";
cmdLengthBytes = commandLength.getBytes("UTF-16LE");
} else {
String iCommandLength = command; // Get the command length
cmdLengthBytes = iCommandLength.getBytes("UTF-16LE");
int commandNewLength = cmdLengthBytes.length-1;
String newLength = "0000" + String.valueOf(commandNewLength);
cmdLengthBytes = newLength.getBytes("UTF-16LE");
}
try {
s = new Socket(host, port); // Connect to server
//Send the command to the server
stream = new DataOutputStream(s.getOutputStream()); // get ready to send
stream.write(cmdLengthBytes); // tell the server how many bytes to expect
System.out.println("Command length sent");
stream.write(commandBytes); // Send the command to papa...
stream.flush(); // guaranteed sending
System.out.println("Command sent");
//Receive the command from the server.
DataInputStream is = new DataInputStream(s.getInputStream()); // get ready to receive
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // prepare to get array
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) { // read the array byte by byte
buffer.write(data, 0, nRead);
}
byte[] dataBytes = buffer.toByteArray(); // get complete array
dataString = buffer.toString("UTF-16LE").substring(8); // get rid of the array length and convert to string
stream.close(); // close the dataStream
s.close(); // close the connection
System.out.println("Disconnected");
} catch (IOException e){
e.printStackTrace();
}
System.out.println("Function Complete");
System.out.println("Server response:" + dataString);
return dataString;
}
}
I have 2 classes (Client and Server) used to implement simple communication in my application. My code is shown below:
Server:
public class Server {
public static void main(String[] ar) {
int port = 1025; // just a random port. make sure you enter something between 1025 and 65535.
try {
ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("enter meter id ");
String line = null;
while (true) {
line = in.readUTF(); // wait for the client to send a line of text.
System.out.println("client send me this id number " + line);
line = keyboard.readLine();
out.writeUTF(line);
out.flush();
//line = in.readUTF();
System.out.println("Waiting for the next line...");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
Client:
public class Client {
public static void main(String[] ar) {
int serverPort = 1025;
String address = "localhost";
try {
InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
System.out.println(" IP address " + address + " and port "
+ serverPort);
Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
// Create a stream to read from the keyboard.
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
System.out.println("ClientConnected.");
System.out.println("enter meter id");
while (true) {
line = keyboard.readLine(); // wait for the user to type in something and press enter.
System.out.println("Sending this number to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush(); // flush the stream to ensure that the data reaches the other end.
line = in.readUTF(); // wait for the server to send a line of text.
System.out
.println("The server was very polite. It sent me this : "
+ line);
System.out.println();
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
My problem is that while testing the program I do get communication between the client and server, but while debugging, with a break point on the out.flush line in Server.java, it does not go to the intended destination. This intended destination being the line line = in.readUTF(); of Client.java. Can anyone help me to solve this?
It is good practice to open the OutputStreams before the InputStreams, on your sockets, as said in this question.
This question also clarifies that.
What I suspect here is your client and server are running in two different JVM processes and java debugger cannot debug two JVM at the same time.
I am new to the forums, and may have posted this to the wrong one - please help a newbie.
As part of project to develop Android App, I need to be able to connect from the app to a set location, which has a small microprocessor based(unchangable) LAN interface, which will accept set commands in hex. The response is given in hex.
Using a sample socket program, which I have tried to modify (see code below), I can see (using wireshark) that the transmitted string is in ASCII, not hex, so I am sending 38 bytes, and not the 18 with the 0x prefix.
I have tried using a LONG, but the value I am trying to send is too large (see String process = '0x.....' midway through the code), and I get 'The literal 0x.... of type int is out of range.
I would appreciate someone pointing me in the right direction.
Thanks
// package bdn;
/* The java.net package contains the basics needed for network operations. */
import java.net.*;
/* The java.io package contains the basics needed for IO operations. */
import java.io.*;
/** The SocketClient class is a simple example of a TCP/IP Socket Client.
* For a detailed explanation of the classes in this project see
* bdn.borland.com/article/0,1410,31995,00.html
*/
public class SocketClient
{
public static void main(String[] args)
{
/** Define a host server */
String host = "192.168.1.199";
/** Define a port */
int port = 3376;
int i = 0;
StringBuffer instr = new StringBuffer();
// String TimeStamp;
System.out.println("SocketClient initialized to " + host + ", port " + port );
try
{
/** Obtain an address object of the server */
InetAddress address = InetAddress.getByName(host);
/** Establish a socket connection */
Socket connection = new Socket(address, port);
/** Instantiate a BufferedOutputStream object */
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
/** Instantiate an OutputStreamWriter object with the optional character
* encoding.
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
// TimeStamp = new java.util.Date().toString();
String process = "0x308101000c00234C51050000000099670007";
System.out.println("Data to be sent is " + process) ;
/** Write across the socket connection and flush the buffer */
osw.write(process);
osw.flush();
System.out.println("Data sent is " + process) ;
/** Instantiate a BufferedInputStream object for reading
* incoming socket streams.
*/
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
/**Instantiate an InputStreamReader with the optional
* character encoding.
*/
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
/**Read the socket's InputStream and append to a StringBuffer */
int c;
for (i = 0; i <= 18; i++ )
{
c = isr.read() ;
instr.append((char) c);
System.out.println("character " + i + " value " + c);
}
/** Close the socket connection. */
connection.close();
System.out.println(instr);
}
catch (IOException f)
{
System.out.println("IOException: " + f);
}
catch (Exception g)
{
System.out.println("Exception: " + g);
}
}
}
I have tried using a LONG, but the value I am trying to send is too large
That's right. The value corresponds to
4225287479528688525220725405996728206163975
and the maximum value of a long is
9223372036854775807
You can store the number in a BigInteger as follows:
String process = "0x308101000c00234C51050000000099670007";
BigInteger bi = new BigInteger(process.substring(2), 16);