NoSuchElementFoundException While Receiving Data from Server - java

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

Related

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

Receiving an array of integers from a server in C to a client in Java

How do I receive an array of integers from a server program written in C, to a client program written in Java?
So I send a number to a server and the server should return me an array of the divisors for that number. Here's my piece of code from the server, in C:
void deservire_client(int c) {
// serving the client
int nr, i=2, nrDiv=0, sirDiv[10]={0,0,0,0,0,0,0,0,0,0};
recv(c, &nr, sizeof(nr), MSG_WAITALL);
nr = ntohs(nr);
while ( i <= nr/2){
if ( nr%i == 0){
sirDiv[nrDiv]=i;
nrDiv+=1;
}
i+=1;
}
send(c, &sirDiv, sizeof(sirDiv), 0);
close(c);
So I tested it out and the array of divisors is being created in the server file. As in, it takes the number I send it, and executes the program correctly, ending up with an array of the number's divisors. I then send the reference to my array back to my client program, in Java. However, I'm pretty sure I'm doing something wrong, since once I input a number in the client, nothing happens.
Here's what I'm doing in my Java client program:
public static void main(String args[]) {
Socket socket = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
int nr = readUnsignedShort("nr = ", reader);
byte[] arr = {0,0,0,0,0,0,0,0,0,0};
writeIntegersToSocket(nr, socket);
readArrayFromSocket(socket);
}
private static void readArrayFromSocket(Socket c) throws IOException {
DataInputStream socketIn = new DataInputStream(c.getInputStream());
int i;
InputStream in = c.getInputStream();
DataInputStream dis = new DataInputStream(in);
byte[] data = new byte[10];
dis.readFully(data);
for(i=0; i < data.length; i++)
System.out.println(" " + data[i]);
}

Client server communication with Java Sockets

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

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