I'm writing a java-c client-server, where the server is in C and the client is in Java. The socket is reused. I don't know why but the client reads the first response from the socket then loops, it's like the client isn't getting "\n". What am I not getting?
The C server sends the response in the format (length:stringlength:string) etc
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Use: java Client server port");
System.exit(1);
}
try{
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Insert input1: ");
String input1 = fromUser.readLine();
System.out.println("Insert input2: ");
String input2 = fromUser.readLine();
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
//BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
InputStream is = s.getInputStream();
BufferedWriter toServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));
do {
String message = "(" + input1.getBytes("UTF-8").length + ":" + input1 + input2.getBytes("UTF-8").length + ":" + input2 + ")";
toServer.write(message);
toServer.flush();
/*reading result from server*/
//String buff;
String output = "";
byte[] buffer = new byte[4096];
int read;
while((read = is.read(buffer)) != -1) {
output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
};
if(output.charAt(0) != '(' || output.charAt(output.length()-1) != ')'){
System.out.println("error using protocol");
}
if(output.indexOf(':')<0){
System.err.println("error using Canonical S-expression!");
System.exit(2);
}
for(int i=output.indexOf(":")+1;i<output.length()-2;i++){
System.out.print(output.charAt(i));
}
System.out.println();
s.close();
System.out.println("Insert input1: ('end' to exit)");
input1 = fromUser.readLine();
} while(!input1.equals("end"));
}
catch(IOException e){
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(100);
}
}
}
Related
I just started learning Java and I am creating a simple TCP application where an input will be entered by a user and this input will be sent from the client side to the server side. This will then be processed and the result will be sent back to the client.
Here are my codes:
Client.java
public class Client {
public static void main(String[] args) {
String hostName = "127.0.0.1";
int port = 23456;
try {
Socket socket = new Socket(hostName, port);
Scanner sc = new Scanner(System.in);
System.out.print("Input command:");
String input = sc.nextLine();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(request);
pw.flush();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String header = br.readLine();
System.out.println(header);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Server.java
public class Server
{
public static void main(String[] args)
{
int port = 23456;
try
{
ServerSocket ss = new ServerSocket(port);
System.out.println("Server is ready to receive command!");
while(true)
{
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new
InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String command = br.readLine();
String response = "";
int val = 0;
try
{
String[] arr = command.trim().split("\\s+");
String operator = arr[0];
int firstNumber = Integer.parseInt(arr[1]);
int secondNumber = Integer.parseInt(arr[2]);
if (operator.equals("add"))
{
val = firstNumber + secondNumber;
response = "The add result is: " + String.valueOf(result);
}
else if (operator.equals("subtract"))
{
val = firstNumber - secondNumber;
response = "The substract result is: " + String.valueOf(result);
}
else if (operator.equals("multiply"))
{
val = firstNumber * secondNumber;
response = "The multiply result is: " + String.valueOf(result);
}
else if (operator.equals("divide"))
{
if (secondNumber != 0)
{
val = firstNumber * secondNumber;
response = "The multiply result is: " + String.valueOf(result);
}
else
{
response = "Error: Divided by zero exception";
}
} else {
response = "Error: Invalid command " + "\"" + operator + "\"";
}
}
catch (NumberFormatException e)
{
System.out.println(command + " is not a number");
}
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(response);
pw.flush();
pw.close();
socket.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
When I run, I get a null as the output.
I am writing tcp client-server program. When the client types "Hello" the server returns a list of files and directories of his current directory. When the client types "FileDownload " it downloads the selected file from the server.
When I type "Hello" it works fine, but when I type "FileDownload ", on the server side it runs twice the else if(received.contains("FileDownload")) block. Because of this the server is sending twice the data which is causing other issues on the client side.
Here is the server code:
public static void main(String[] args) throws IOException {
ServerSocket servSock = new ServerSocket(1333);
String received="";
String[] s = null;
File[] f1;
int i=0;
File f=new File(System.getProperty("user.dir"));
f1=f.listFiles();
for(File f2:f1) {
if(f2.isDirectory())
System.out.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
System.out.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
while (true) {
Socket client = servSock.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
s=f.list();
while(true) {
received = reader.readLine();
if(received.equals("END")) break;
if(received.equals("Hello")) {
System.out.println("Hello-Start");
int length=f1.length;
pw.println(length);
i=0;
for(File f2:f1) {
if(f2.isDirectory())
pw.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
pw.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
pw.println("Options: " + "\tFileDownload <FID>" + "\tFileUpload <name>" + "\tChangeFolder <name>");
System.out.println("Hello-End");
}
else if(received.contains("FileDownload")) {
System.out.println("FileDownload-Start");
int j=-1;
try {
j=Integer.parseInt(received.substring(13).trim());
}catch(NumberFormatException e) {
System.err.println("error: " + e);
}
if(j>0 && j<s.length) {
FileInputStream fi=new FileInputStream(s[j]);
byte[] b=new byte[1024];
System.out.println("file: "+s[j]);
pw.println(s[j]);
fi.read(b,0,b.length);
out.write(b,0,b.length);
System.out.println("FileDownload-End");
}
}
Here is the client code:
public static void main(String[] args) throws IOException {
if ((args.length != 2))
throw new IllegalArgumentException("Parameter(s): <Server> <Port>");
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner sc = new Scanner(System.in);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
while(true) {
String msg="", received="";
String length;
msg = sc.nextLine();
pw.println(msg);
if(msg.equals("END")) break;
if(poraka.equals("Hello")) {
System.out.println();
length = reader.readLine();
for(int i=0;i<Integer.parseInt(length);i++) {
received = reader.readLine();
System.out.println(received);
}
System.out.println("\n"+reader.readLine());
}
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg);
byte[] b=new byte[1024];
File file=new File(reader.readLine().trim());
System.out.println(file.getName().trim());
FileOutputStream fo=new FileOutputStream("D:\\Eclipse WorkSpace\\proekt\\src\\client\\"+file.getName().trim());
System.out.println("file: "+file.getName().trim());
in.read(b,0,b.length);
fo.write(b,0,b.length);
System.out.println("FileDownload-End");
}
I could not find what's causing this issue, so any help possible would be very highly appreciated!
It is because your client requests the data twice:
msg = sc.nextLine();
pw.println(msg); // <-- this is the first time
and then later
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg); // <-- this is the second time
How do I get and store a string produced every 2 seconds using readline()? Socket programming.
#Receiver
try {
while (true) {
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
//payload = br.readLine();
// payload = String.parseString(br.read(char getdata[],0, 65535));//valueOf(char)
//br.reset();
int payload_length = payload.length();
System.out.println("Message sent from client: " + payload + ":: Length ::" + payload_length);
if (payload_length == stringLength) {
// for(int k=0;k>=s;k++){
System.out.println("String length matching");
String Query1 = "INSERT INTO RpiBuffer (string) values(?)"; //,(payload);
pst1 = conn.prepareStatement(Query1);
// pst1.setInt(1, id);
pst1.setString(1, payload);
//pst1.setInt(3,isSend);
pst1.executeUpdate();
System.out.println("Query 1 Executed::" + pst1);
// }
} else {
System.out.println("String length not matching");
}
/* ---------------------------------------------------------------------*/
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
// bw.write(returnedMessage);
bw.newLine();
// System.out.println("Message replied to client: "+returnedMessage);
bw.flush();
check_internet();
}
} catch (IOException e) {
System.out.println("Exception in receive_data())::" + e);
}
#Sender
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class EchoClient {
public static void main(String[] args) throws InterruptedException {
String hostName = "127.0.0.1";
int portNumber = 3002;
int StringLength = 22;
int i=0;
while(true){ //for(i=0;i<99;i++){
try {
Socket echoSocket = new Socket(hostName, portNumber);
// PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream()));
BufferedWriter out= new BufferedWriter( new OutputStreamWriter(echoSocket.getOutputStream()));
String s1="1231231231231231231234",s2="0001110001110001110001",s3="0101010101",s4="1111000011110000111100";
out.write(s1);System.out.println("send data1 successfully????? ");TimeUnit.SECONDS.sleep(2);
out.write(s2);System.out.println("send data2 successfully????? ");TimeUnit.SECONDS.sleep(2);
out.write(s3);System.out.println("send data3 successfully????? ");TimeUnit.SECONDS.sleep(2);
out.write(s4);System.out.println("send data4 successfully????? ");TimeUnit.SECONDS.sleep(2);
/* String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}*/
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
//System.exit(1);
}
}
}
}
run:
initializing program.....rpibuffer.RpiBuffer#7852e922
Server start at port 3002.
BUILD STOPPED (total time: 46 seconds)
why won't my client side accept anymore input, after inputing one FIX message. The client will send a FIX message to the server side, and the server will check for errors, and send back a message back to the client if it has errors or not on the FIX message.
The problem comes when I try to send another FIX message from the client side, prior to sending one, it won't allow me to send anything.
Client Program
public class TcpClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("WA1235"); //127.0.0.1
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 57634.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 57634);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
System.out.println(in.readLine());
if (userInput.equals("Bye.")){
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
Server Program
public static void main(String[] args) throws IOException{
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\Downloads\\orders.csv";
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(57634);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
out.println(outputLine);
input1.close();
input2.close();
input3.close();
input4.close();
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
method
public static String compareClientFixCSV(String[] cTag, String[] cValue, String[] csvTag, String[] csvValue){
int size = csvTag.length;
int size2 = csvTag.length;
int size3 = cValue.length;
int size4 = csvValue.length;
System.out.println("cTag size : " + size + ", csvTag: " + size2);
System.out.println("csvTag value : " + size3 + ", csvValue: " + size4);
String output = null;
for(int i = 0; i<= size-1; i++){
if(cTag[i].equals(csvTag[i]) == false ){
output = ("Error in tag " + cTag[i]);
}
else if(cValue[i].equals(csvValue[i]) == false){
output = ("Error in value " + cValue[i]);
}
else{
output = ("No errors");
}
}
return output;
}
Just a quick look at the code, I see the client waits for 2 lines:
System.out.println(in.readLine());
System.out.println(in.readLine());
and the server sends only 1:
out.println(outputLine);
May be that is the problem.
I'd also will enclose the reading part of the client in a try ... catch ... finally block, like this:
try
{
while (true)
{
System.out.print("input: ");
userInput = stdIn.readLine();
if (userInput == null) break;
out.println(userInput);
System.out.println(in.readLine());
System.out.println(in.readLine());
if (userInput.equals("Bye."))
{
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// any of these lines could raise an exception as well.
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
I just want to send a simple string to the client side, however it is not doing so.
It will just skip the out.println statement and just do the rest of the program properly.
Is out.println the wrong statement for sending to the client from the server side?
I just want to send "hello" by using this code.
out.println("hello");
program for server side
public class TcpServerCompareCSV {
public static void main(String[] args) throws IOException{
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\Downloads\\orders.csv";
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(57634);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
Boolean comp;
while ((inputLine = in.readLine()) != null)
{
***out.println("hello");***
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
System.out.println ("Server: " + inputLine);
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
comp = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
if(comp)
out.println(noError);
else
out.println(Error);
input1.close();
input2.close();
input3.close();
input4.close();
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
program for client side
public class TcpClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("WA12345"); //127.0.0.1
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 57634.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 57634);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye.")){
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
You are never reading from your socket input stream in your client program (created by statementin = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); ), so you never actually try to receive it.
You need a in.readLine() in your client program in the loop, after
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
It should look like this:
System.out.println(in.readLine());