How to fix printing server side output in client side - java

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

Related

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

Simple TCP client/server program in Java

Hi I'm having a small problem with my program which is a simple client/server. The client sends the contents of a textfile to the server. The text file is just ints and then the server is suppose to send back the largest prime number less than each int in the text file(if its prime it should just send back the prime number and do nothing). So for instance lets say the text file is 5 15 28. The result after running the program should be 5 13 23.
Here's my code for the Client side:
public class TCPClient {
public static void main(String[] args) throws Exception{
try{
Socket mySock = new Socket("127.0.0.1", 12001);
BufferedReader in = new BufferedReader(
new InputStreamReader(mySock.getInputStream()));
PrintStream out = new PrintStream( mySock.getOutputStream());
Scanner scan = new Scanner(new File(args[0]));
String msg = scan.nextLine();
out.println(msg);
System.out.println(in.readLine());
mySock.close();
}catch (Exception e){
}
}
}
Here's my code for the server side:
public class TCPServer {
public static void main(String[] args) throws Exception {
try{
ServerSocket mySock = new ServerSocket(12001);
Socket client = mySock.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream( client.getOutputStream());
String[] arr = in.readLine().split(" ");
int[] intarr = new int[arr.length];
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
out.println(intarr[i]);
}else{
while (!prim(--intarr[i])){
}
out.println(intarr[i]);
}
}
client.close();
mySock.close();
}catch (Exception e){
}
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
When I run this program my output is only the first number in the text file. So if my text file is 1 3 5. My output is just 1. However, my prime algorithm is at least working because if my text file is 8 for instance, my program will return 7. Does anyone know why this is happening?
By change your server code to a simple test and printing to System.out
String[] arr = "1 3 5 6".split(" ");
int[] intarr = new int[arr.length];
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
System.out.println(intarr[i]);
}else{
while (!prim(--intarr[i])){
}
System.out.println(intarr[i]);
}
}
you can see that it works OK, but in your code, your output in writing using println, so your client needs to loop System.out.println(in.readLine()); or change your server to write using one line and some delimiter
In TCPServer, when printing to outputstream use print instead of println
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
out.print(intarr[i]); // use print instead of println
}else{
while (!prim(--intarr[i])){
}
out.print(intarr[i]); // use print instead of println
}
}

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

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

How to return condition in a switch statement to while?

How to return action to while loop in a switch statement ? The client is unable to return to while statement. I meant to say, whenever response comes from server, the client must start from while loop again, so that client can select his choices. Is it a problem of System.out ? (Note: It's a copied code from others) Here are the client and server :
Client:
.............
while (true) {
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
..........
case 2: // for viewing files in the client's directory
try{
Socket mysoc = new Socket("localhost", 9001);
String user_name = username;
DataOutputStream ToServer = new DataOutputStream(mysoc.getOutputStream());
ToServer.writeBytes(user_name + '\n');
BufferedReader FromServer = new BufferedReader(new InputStreamReader(mysoc.getInputStream()));
String line = null;
while ((line = FromServer.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
break;
............
}
Server:
import java.io.*;
import java.net.*;
class DirList
{
public static void main(String argv[]) throws Exception
{
String clientString;
//String replyString;
ServerSocket welcomeSoc = new ServerSocket(9001);
while(true)
{
Socket connectionSocket = welcomeSoc.accept();
BufferedReader FromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter ToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
clientString = FromClient.readLine();
System.out.println("Received view songs request from : " + clientString);
String path = "/home/sri/Songs/";
String text="";
File f = new File(path);
File[] listOfFiles = f.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
text = listOfFiles[j].getName();
ToClient.println(text);
}
}
}
}
}
Why don't you label the outermost while like this..
outer: while(true)
and use the continue keyword to return to the label.
continue outer;
try to close your PrintWriter and Socket in the Server code after they finished their task.
#Sri, about the question you've asked in the comment:
by Socket I meant connectionSocket. ServerSocket will remain there during your server life time. But you will have a new connectionSocket for each user. so each connectionSocket will serve only a single client.

Categories