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.
Related
I am trying to send an object from my server and then receiving it/displaying it on the client side. The object in question has a few parameters tied to it, such as int values and string values. Do I also need to have a version of my server class on the client side in which to store the values from the input stream?
I have tried the following:
Server
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
Server server = new Server(val1, val2, str1, str2);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(server );
// printWriter.println(server );
serverOutputStream.writeObject(server );
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
server.doSomething(symbol, scanner);
// printWriter.println(scanner.nextInt());
System.out.println(server);
// printWriter.println(server);
serverOutputStream.writeObject(server);
if (server.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
Client
public static void main(String[] args) throws Exception {
// if (args.length != 1) {
// System.err.println("Pass the server IP as the sole command line argument");
//
// return;
// }
try (Socket socket = new Socket("127.0.0.1", 59898)) {
System.out.println("Enter a move: ");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
Object object = serverInputStream.readObject();
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
serverOutputStream.writeObject(object);
}
}
}
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()? 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();
}
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)