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);
Related
I have a integration test that sends 800 messages to a client. The client receives all the messages fine. The issue is my test fails periodically because the socket (towards the end of the messages), reads no bytes (-1) from the stream, closes the socket, reopens the socket, and gets the bytes. The test 'completes' before the final bytes are read (and so fails), but I can see in the log the last messages do get to the client successfully. This is intermittent. It happens about every half dozen runs or so. In other words, maybe 5 runs straight will get no errors (the socket never had to be closed/re-opened), but the 6th run will have this issue.
So far I have tried increasing/decreasing message sending speed.
Server:
try
{
srvr = new ServerSocket(PORT);
Socket socket = srvr.accept();
...
OutputStream out = socket.getOutputStream();
for (String msg : Messages)
{
byte[] bytes = new BigInteger(msg, BASE_16).toByteArray();
out.write(bytes);
// Delay so client can keep up.
sleep(SOCKET_CLIENT_DELAY);
}
}
catch (IOException ioe)
{
fail(ioe.getMessage());
}
finally
{
handleClose(srvr);
}
Client:
#Override
public void run()
{
final long reconnectAttemptWaitTimeMillis = 5_000;
Socket socket = null;
while (true)
{
try
{
socket = new Socket(host, port);
boolean isConnected = socket.isConnected();
if (isConnected)
{
read(socket);
}
}
catch (ConnectException ce)
{
LOGGER.warn(
"Could not connect to ADS-B receiver/antenna on [" + host + ":" + port
+ "]. Trying again in 5 seconds...");
try
{
sleep(reconnectAttemptWaitTimeMillis);
}
catch (InterruptedException ie)
{
LOGGER.error(ie.getMessage(), ie);
break;
}
}
catch (IOException ioe)
{
LOGGER.error(ioe.getMessage(), ioe);
}
}
LOGGER.info("A total of " + totalEnqueued + " ADS-B messages were enqueued.");
}
/**
* Reads binary ADS-B messages from the {#link Socket}. Assumption is the given {#link Socket} is connected.
*
* #param socket
* where to read ADS-B messages from.
*/
private void read(final Socket socket)
{
LOGGER.info(getName() + " connected to " + host + ":" + port);
DataInputStream in = null;
try
{
in = new DataInputStream(socket.getInputStream());
while (true)
{
byte[] rawBuffer = new byte[MESSAGE_BUFFER_SIZE];
int bytesRead = in.read(rawBuffer);
if (bytesRead == -1)
{
LOGGER.warn("End of stream reached.");
break;
}
/*
* The Mode-S Beast receiver's AVR formatted output for every message begins with 0x1A.
*/
if (rawBuffer[0] == MODE_S_BEAST_PREFIX_NUM)
{
/*
* AdsbDecoder will expect a hexadecimal String representation of the ADS-B message
* without the prefix and suffix.
*
* First, we will convert the raw bytes into a hexadecimal String.
*
* Then, we will remove the Mode-S Beast metadata from the AVR format.
*
* For example:
* "1A33000000000000008DA44E325915B6B6A2FACB45988A" will look like "8DA44E325915B6B6A2FACB45988A"
*
* Finally, we enqueue the ADS-B hex message.
*/
// 1A33000000000000008DA44E325915B6B6A2FACB45988A
String modeS = new BigInteger(rawBuffer).toString(BASE_16).toUpperCase();
// Remove Mode-S Beast info
final int modesBeastPrefixLength = 18;
String adsbMessage = modeS.substring(modesBeastPrefixLength, modeS.length());
LOGGER.info("Message read from receiver/antenna: [" + adsbMessage + "]");
rawAdsbMessages.offer(adsbMessage);
++totalEnqueued;
}
}
}
catch (
IOException ioe)
{
LOGGER.error("Problem encountered reading from Socket. " + ioe.getMessage());
}
finally
{
if (Objects.nonNull(in))
{
try
{
in.close();
}
catch (IOException ex)
{
LOGGER.error("Problem encountered closing the Socket reader. " + ex.getMessage());
}
}
}
}
I expect to not see the bytesRead value become -1 and it have to re-establish the connection since this is all in one test. I have very limited knowledge of socket programming, so maybe this is an unrealistic expectation. If so, please tell me why. Maybe putting a buffered reader/writer in .?? Any suggestions would be fantastic.
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;
}
}
In the below codes,I am trying to let the server-side to select the file from the client and sends it, so basically all the work is done on the server side. the program works by running the server first wait for client to run, make a connection, then the server sends the place of the file to the client-side outReader.write("B://ghassar/ghassar.txt"); the client reads the location and sends the file. I have run the debug and once the server reads this code String filename = inReader.readLine(); it stops and it gets in like a loop, can anyone help me to solve the problem
/ Server.java
/*
* Server waits for a connection to be established by client
*
*/
import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[])throws Exception
{
System.out.println("Server running...");
/* Listen on port 5555 */
ServerSocket server = new ServerSocket(222);
/* Accept the sk */
Socket sk = server.accept();
System.out.println("Server accepted client");
// to recive from client
InputStream input = sk.getInputStream();
//read what is coming
BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
//write to client
BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));
outReader.write("B://ghassar/ghassar.txt");
outReader.flush();
/* Read the filename */
String filename = inReader.readLine();
if (filename.equals("ghassar.txt") ){
/* Reply back to client with READY status */
outReader.write("READY\n");
outReader.flush();
}
/* Create a new file in the libya directory using the filename */
FileOutputStream wr = new FileOutputStream(new File("B://libya/ "+ filename));
byte[] buffer = new byte[sk.getReceiveBufferSize()];
int bytesReceived = 0;
while((bytesReceived = input.read(buffer))>0)
{
/* Write to the file */
wr.write(buffer,0,bytesReceived);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]){
Client clientForm = new Client();
clientForm.action();
}
public void action() {
try{
/* Try to connect to the server on localhost, port 5555 */
Socket sk = new Socket("localhost", 222);
OutputStream output = sk.getOutputStream();
/* the steam to send the staff*/
OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream());
/* steam to recive staff */
BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
String serverStatus = inReader.readLine(); // Read the first line
String filename = serverStatus;//fileDlg.getSelectedFile().getAbsolutePath();
outputStream.write("ghassar.txt");
outputStream.flush();
/* If server is ready, send the file */
if ( serverStatus.equals("READY") ){
FileInputStream file = new FileInputStream(filename);
byte[] buffer = new byte[sk.getSendBufferSize()];
int bytesRead = 0;
while((bytesRead = file.read(buffer))>0)
{
output.write(buffer,0,bytesRead);
}
output.close();
file.close();
sk.close();
System.out.println("File sent");
}
}
catch (Exception ex){
/* Catch any errors */
System.out.println("not File sent");
}
}
}
I suggest you to use PrintWriter instead of BufferedWriter. There is no need to call flush after each line and simply use println() method along with auto-flush feature to add a new line as well.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.
These methods use the platform's own notion of line separator rather than the newline character.
There is no need to append \n in the message itself.
Sample code:
// here true means auto flush when `println()` method is called
PrintWriter w=new PrintWriter(new OutputStreamWriter(sk.getOutputStream()),true);
w.println(message);
Possible cause in the code:
The problem may be at below lines where \n is not added in the end of the string in write() method before flushing and at client side the method readLine() is used to read it.
BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));
outReader.write("B://ghassar/ghassar.txt");
outReader.flush();
Note: you can use BufferedWriter#newLine() instead of \n that writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
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.