Why won't my statement send to client side? - java

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());

Related

My Java client isn't reading the whole Socket response

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);
}
}
}

How do I get and store a string produced every 2 seconds using readline()

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)

Client not able to receive messages from Server Socket programming Java

I am trying to make a chat system through terminal. One computer acts as server, the other as client.
Here is my code for Client side :
try
(
Socket s = new Socket(hostname,port);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String input;
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
// out.close();
// stdIn.close();
// s.close();
}
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");
System.exit(1);
}
Here is my code for Server side:
System.out.println ("New communication thread started.");
try
{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String input;
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
}
catch (IOException exx)
{
System.err.println("Some problem");
System.exit(1);
}
You are using stdIn.readLine() on System.in but that stream can never terminates (of course).
So you should change your condition.
while ((input = stdIn.readLine()) != null) // Your problem is here
Have you checked if you reach the second while?
Try this in both server and client:
input = stdIn.readLine();
out.println(input);

java socket programming chat

I'm Playing with a simple Client and Server application using socket, and i attempt to print a message in the console and get a response from the server but nothing shows up, i'm fairly new to sockets so i assume i have a logical error. It's a simple app that i want the client to prompt a user a user for a command (in my case an input string where the server will perform an action based on the 'thcharacter), send it to the server and just display the server response.I'm pretty sure my client isn't correct, can someone points out why i can't write anything from the client console.
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket= new Socket();
BufferedReader in = null;
String msg;
int port = 2222;
try {
System.out.println("CLient wants to connect on port: "+port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try{
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
String text = null;
output.print(text);
while ((text = input.readLine()) != null){
System.out.println("Client "+text);
}
socket.close();
System.out.println("Client Exiting");
}
catch(IOException e) {
System.out.println(e);
}}
}
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;//Integer.parseInt(args[0]);
try{
sSocket = new ServerSocket(port);
} catch(IOException e){
System.out.println(e);
}
while(true){
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: "
+InetAddress.getLocalHost().getHostAddress() +""
+ " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if(msg != null){
if(msg.charAt(12)=='4'){
System.out.println("reading message "+msg+" ");
output.print("Bye");
sSocket.close();
System.out.println("Server exits");
}else{
if(msg.charAt(12)=='0'){
System.out.println("reading message "+msg+" ");
output.print("OK");
}else if (msg.charAt(12)=='1'){
System.out.println("reading message "+msg+" ");
//Should return IP address
output.print(clientSocket.getInetAddress());
}else if (msg.charAt(12)=='2'){
System.out.println("reading message "+msg+" ");
for(int i = 1; i<=10; ++i){
output.print(i);
output.print(" ");
}
}else if (msg.charAt(12)=='3'){
System.out.println("reading message "+msg+" ");
output.print("GOT IT");
}else{
System.out.println("*******************");
}
}
}
sSocket.close();
System.out.println("Server exits");
}
catch(IOException e) {
System.out.println("accept failed");
System.exit(1);
}
System.out.println("Hello world");
}
}
}
I took some liberties with your code and changed it a bit. It is by no means a perfect version of what you've supplied; however, it should get you pointed in the right direction. These were the problems that were solved:
MyClient was never prompting for user input.
MyServer was sending strings without newlines. MyClient was expecting strings with newlines.
In MyServer, the main socket was being closed at the bottom of the loop. I believe you intended to close the client socket so that the server would loop around and process another client.
In MyServer, you're checking the 13th character of the user's input (because you were indexing the 12th byte (zero based) of the string. I put in brute-force protection against checking the 13th byte of strings that are too short.
Again, I simply corrected certain problems in your code. I may have altered it beyond what your true goals actually are. These examples are intended to get you going on your way...
MyClient.java:
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = new Socket();
int port = 2222;
try {
System.out.println("CLient wants to connect on port: " + port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
// Get a line of input from the user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputFromUser = br.readLine();
// Send that line of input to MyServer.
output.println(inputFromUser);
// Print out the response from MyServer.
System.out.println("SERVER RESPONSE: " + input.readLine());
socket.close();
System.out.println("Client Exiting");
} catch (IOException e) {
System.out.println(e);
}
}
}
MyServer.java:
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;// Integer.parseInt(args[0]);
try {
sSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if (msg != null) {
if (msg.length() > 12 && msg.charAt(12) == '4') {
System.out.println("reading message " + msg + " ");
output.println("Bye");
System.out.println("Server exits");
} else {
if (msg.length() > 12 && msg.charAt(12) == '0') {
System.out.println("reading message " + msg + " ");
output.println("OK");
} else if (msg.length() > 12 && msg.charAt(12) == '1') {
System.out.println("reading message " + msg + " ");
// Should return IP address
output.println(clientSocket.getInetAddress());
} else if (msg.length() > 12 && msg.charAt(12) == '2') {
System.out.println("reading message " + msg + " ");
for (int i = 1; i <= 10; ++i) {
output.println(i + " ");
}
} else if (msg.length() > 12 && msg.charAt(12) == '3') {
System.out.println("reading message " + msg + " ");
output.println("GOT IT");
} else {
System.out.println("*******************");
// Invalid question from client, I guess.
output.println("HUH?");
}
}
// Make sure output is flushed to client. It will be, but
// just in case...
output.flush();
}
// We're done with this client. Close his socket.
clientSocket.shutdownOutput();
clientSocket.close();
System.out.println("Closed client socket");
}
catch (IOException e) {
System.out.println("accept failed");
e.printStackTrace();
System.exit(1);
}
System.out.println("Hello world");
}
}
}
The problem is that nobody is actually sending any lines. This is what your client does:
output.print(text); //sends null
while ((text = input.readLine()) != null){ //waits to receive a line
This last part is where your client stops because it waits for input that the server never sends. So here is where the server stops:
msg = input.readLine(); //waits to recieve a line
It never reads in null because you didn't send a line (e.g. ending with '\n'). You can easily fix this problem by replacing your output.print() calls with output.println() calls, so that your readers know the line has end and can be read in now.

why won't my client side accept anymore input

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();
}

Categories

Resources