Client server communication with Java Sockets - java

i built a program with client and server sockets in java that gets a number from the client, and multiply it by 2.
the code doesn't let me put a number in the client side.
code:
Client:
public class cli {
public static void main(String args[]) throws UnknownHostException, IOException{
Scanner in = new Scanner(System.in);
int number,temp;
Socket s = new Socket("127.0.0.1", 1342);
Scanner c1 = new Scanner(s.getInputStream());
System.out.println("Enter any number");
number = in.nextInt();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(number);
temp = c1.nextInt();
System.out.println(temp);
in.close();
s.close();
c1.close();
}
}
Server:
public class ser {
public static void main(String args[]) throws IOException{
ServerSocket s1 = new ServerSocket(1342);
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
int number = sc.nextInt();
int temp = number * 2;
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
ss.close();
sc.close();
s1.close();
}
}

You should use DataInputStream to read your int and DataOutputStream to write it, it is more appropriate in your case than a Scanner. You should also consider using try-with-resourses statement to properly close your resources.
Your code will then be much easier to read and to maintain which is the best way to avoid bugs.
Server:
public class ser {
public static void main(String args[]) throws IOException {
try (ServerSocket s1 = new ServerSocket(1342);
Socket ss = s1.accept();
DataInputStream sc = new DataInputStream(ss.getInputStream());
DataOutputStream p = new DataOutputStream(ss.getOutputStream());
) {
p.writeInt(sc.readInt() * 2);
}
}
}
Client:
public class cli {
public static void main(String args[]) throws IOException {
try (Scanner in = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1342);
DataInputStream c1 = new DataInputStream(s.getInputStream());
DataOutputStream p = new DataOutputStream(s.getOutputStream());
){
System.out.println("Enter any number");
int number = in.nextInt();
p.writeInt(number);
System.out.println(c1.readInt());
}
}
}
Output:
Enter any number
12
24

Related

Can I type input from keyboard to Scanner.nextLine() waiting in .class file by Runtime class?

//Run App from Path
public static void runApp(String path) throws IOException {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(path);
InputStream inputStream = process.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
int n1;
char[] c1 = new char[1024];
StringBuffer standardOutput = new StringBuffer();
while ((n1 = isr.read(c1)) > 0) {
standardOutput.append(c1, 0, n1);
}
System.out.println("Standard Output: " + standardOutput.toString());
}
//Main Method
public static void main(String[] args) throws IOException {
String path = "java -classpath E:\\code\\java\\ctppmhw\\bin\\ App";
runApp(path);
}
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("String is: " + str);
sc.close();
}
}
When I run the main method contains runApp() method, it's waiting for me to type from the keyboard, but I can't type it on my console. What can I do to fix this?
I added this code into the above code block and it works:
OutputStream fos = process.getOutputStream();
DataOutputStream dos = new DataOutputStream(fos);
dos.writeBytes("5");
dos.flush();
dos.close();
RunApp(main process) starts App.main(sub process), by
Process process = runTime.exec(path);
InputStream inputStream = process.getInputStream();
process.inputStream, process.errorStream is (sub process)'s standard output and error output. you can't use them to write back to (sub process) within (main process),
you may try (sub process)process.outputStream.

How to fix printing server side output in client side

I have a server code whereby the output is printed half and not all is printed on the client side
The server code is :
public static void main(String args[]) throws IOException {
int number;
String temp = null;
ServerSocket s1 = new ServerSocket(1306);
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
number = sc.nextInt();
//temp = number*5;
switch (number) {
case 2304: {
temp = "RESEARCH METHODOLOGY "
+ "\n Madam Cecelia";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
break;
}
case 2404: {
String temp = "PROJECT MANAGEMENT\n PATRICK Barack";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
break;
}
case 2305: {
String temp = "HUMAN COMPUTER INTERACTION\n Dr. HADULLO";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
break;
}
}
The client code is as follows which works when client send the unit code and then server responds by the output from the clients request.
Scanner sc1= new Scanner(System.in);
try {
Socket so= new Socket("127.0.0.1", 1306);
System.out.println("Enter unit code");
int number= sc1.nextInt();
PrintStream p = new PrintStream(so.getOutputStream());
p.println(number);
Scanner sc2= new Scanner(so.getInputStream());
String temp= sc2.next();
System.out.println(temp);
Try flush()ing the PrintStream: javadoc

execute different class to another

I'm having a really hard time to make this project to run but keep on failling....
so what I want to do is send the String or all the message that other class "bankingmain.java" to client class.
The source I create is
==========================================================================
package main;
import java.util.Scanner;
public class BankingMain {
public static void main(String[] args)throws IOException {
ServerSocket ss = new ServerSocket(9000);
System.out.println("Server is waiting");
while(true) {
Socket s = ss.accept();
InetSocketAddress clientip =
(InetSocketAddress)s.getRemoteSocketAddress();
System.out.println
(clientip.getHostString() + " client has connected");
try{
OutputStream stream = s.getOutputStream();
stream.write(bak);
}catch(Exception e){
e.printStackTrace();
}
InputStream is = s.getInputStream();
byte b [] = new byte[100];
int cnt = is.read(b);
String input = new String(b, 0, cnt);
System.out.println
("client ip = " + input);
OutputStream os = s.getOutputStream();
input = input+"(input)";
byte b2[] = input.getBytes();
os.write(b2);
}
}
}
===========================================================
this is gonna be a server
and the method that I', trying to exeicute and print it out to client will be below
public static void main(String[] args) {
System.out.println("************************************************");
System.out.println("1. login\t\t2. id / find password");
//System.out.println("2. id/find password");
System.out.println("3. signup\t\t4. quit");
//System.out.println("4. quit");
System.out.println("************************************************");
System.out.print("put number: ");
Scanner sc = new Scanner(System.in);
String menu = sc.nextLine();
if (menu.equals("1") || menu.equals("login")) {
new view.LoginView().input();
}
else if (menu.equals("2") || menu.equals("id") || menu.equals("password") || menu.equals("find")) {
new view.MemberSearchView().input();
}
else if (menu.equals("3") || menu.equals("signup")) {
new view.MemberInsertView().input();
}
else if (menu.equals("4") || menu.equals("quit")) System.exit(0);
else System.out.println();
}
}
there are a vo,dao that everything runs fine but when I'm trying to extend to be server and client it doesn't work that I assume...
I am stuck in this part... help me out

NoSuchElementFoundException While Receiving Data from Server

public class cli
{
public static void main(String args[]) throws IOException
{
int no,rec;
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1400);
Scanner sc1 = new Scanner(s.getInputStream());
System.out.println("Enter any number");
no = sc.nextInt();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(no);
rec = sc1.nextInt();
System.out.println("Receive number is " + rec);
}
}
I am sending a number to server and getting a number that is multiple of the number sent, but the problem I am facing is here: the rec=sc1.nextInt() statement gives me NoSuchElementFoundException. What am I doing wrong? Thanks.
Server code:
public class Server {
public static void main(String args[]) throws IOException {
ServerSocket ss = new ServerSocket(1400);
System.out.println("Waiting ");
Socket s1 = ss.accept();
Scanner sc = new Scanner(s1.getInputStream());
int a = sc.nextInt();
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
ps.flush();
System.out.println("Got and sent Sucessfull " + temp);
ss.close();
}
}
The problem is that you are not writing a number to the server's output, but a character with the 2*a code.
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
Here invoking write(temp) writes the character with the temp code to the output. For example, if a was 16, then temp is 32, so writing this to the PrintWriter actually writes a space character. If you want to write the number as a string, do this:
ps.write(Integer.toString(temp));

While Loop not working as it should be

Client will request for a file, if the file exist in server then the server send the file and give a confirmation message. So i want to take input using the main while loop but it stops working after first iteration,
client side
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class WebClient {
public static void main(String[] args) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
String req;
System.out.println("Do you want to search? (Y/N): ");
Scanner user_input = new Scanner(System.in);
req = user_input.next();
while (req.equals("Y")) {
Socket clientSocket = new Socket("localhost", 2000);
System.out.println("Enter the file name: ");
String file = inFromUser.readLine();
DataOutputStream serverOutput = new DataOutputStream(clientSocket.getOutputStream());
serverOutput.writeBytes(file + '\n');
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Text from the file: ");
while (true) {
String data = serverInput.readLine();
if (data == null) {
break;
}
System.out.println(data);
}
clientSocket.close();
System.out.println("Do you want to search again? (Y/N): ");
req = user_input.next();
}
}
}
server side
import java.io.*;
import java.net.*;
public class WebServer {
public static void main(String[] args) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(2000);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String file = inFromClient.readLine();
System.out.println("Client Request: " + file); //Show The Client Request File
String path = ("E://From Varsity//4.2//Lab//Network Programming//Java trying//New TCP-Client+Server//tcp")+ "/" + file ;
File objfile = new File(path);
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
if (objfile.exists())
{
String readfile = rfile(path);
outToClient.writeBytes("\n" +readfile + "200 ok \n"); // when exact file find
}
else
{
outToClient.writeBytes("404 The Requested File not found \n"); // file not found
}
}
}
public static String rfile(String file_N) throws Exception
{
StringBuilder app = new StringBuilder();
BufferedReader bufferR = new BufferedReader(new FileReader(file_N));
try
{
String line = bufferR.readLine(); // read file from buffer
while (line != null) {
app.append(line); // append the line
app.append("\n");
line = bufferR.readLine();
}
}
finally
{
bufferR.close();
}
return app.toString();
}
}
Any help will be appreciated , thanks in advance
java.net.Socket is blocking. It'll block until it receives a close (the call to readLine() blocks until more data is available)
3 solutions:
Simplest: add outToClient.close() after the write.
Nonblocking: Use java.nio.SocketChannel/java.nio.ServerSocketChannel
Threaded: Create a new thread each time ServerSocket.accept() fires with the Socket object from accept.

Categories