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
Related
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
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
i have a very simple assignment in which i am supposed to send 2 integers into a socket, which sends their sum back to the "client".
this is my client:
int a,b,sum;
try
{
Socket Server_info = new Socket ("localhost", 15000);
BufferedReader FromServer = new BufferedReader (new InputStreamReader(Server_info.getInputStream()));
DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
while (true)
{
System.out.println("Type in '0' at any point to quit");
System.out.println("Please input a number");
a = User_in.nextInt();
ToServer.writeInt(a);
System.out.println("Please input a second number");
b = User_in.nextInt();
ToServer.writeInt(b);
sum = FromServer.read();
System.out.println("the sum of " +a+ " and " +b+ " is: " +sum );
if (a==0 || b==0)
break;
}
this is my socket handler:
int num1=0 ,num2=0, sum;
try
{
BufferedReader InFromClient = new BufferedReader (new InputStreamReader(soc_1.getInputStream()));
DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
while (true)
{
num1 = InFromClient.read();
num2 = InFromClient.read();
sum = num1 + num2 ;
OutToClient.writeInt(sum);
}
}
catch (Exception E){}
After the first Integer input upon running the client i get this:
Type in '0' at any point to quit
Please input a number
5
Connection reset by peer: socket write error
i think the problem lays at the socket receiving side, i must be doing something wrong. any suggestions?
You can use DataInputStream and DataOupStream objects but I find it simpler to user a pair of Scanner and PrintWriter objects both at the server side and client side. So here is my implementation of the solution to the problem:
The Server Side
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoServer {
private static ServerSocket serverSocket;
private static final int PORT = 1234;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException ioex){
System.out.println("Unable to attach to port!");
System.exit(1);
}
handleClient();
}
private static void handleClient()
{
Socket link = null; //Step 2
try {
link = serverSocket.accept(); //Step 2
//Step 3
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
int firstInt = input.nextInt();
int secondInt = input.nextInt();
int answer;
while (firstInt != 0 || secondInt != 0)
{
answer = firstInt + secondInt;
output.println(answer); //Server returns the sum here 4
firstInt = input.nextInt();
secondInt = input.nextInt();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
System.out.println("Closing connection...");
link.close();
}
catch (IOException ie)
{
System.out.println("Unable to close connection");
System.exit(1);
}
}
}
}
The Client Side
import java.net.*;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String[] args) {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException uhEx) {
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer() {
Socket link = null; //Step 1
try {
link = new Socket(host, PORT); //Step 1
//Step 2
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
//Set up stream for keyboard entry
Scanner userEntry = new Scanner(System.in);
int firstInt, secondInt, answer;
do {
System.out.print("Please input the first number: ");
firstInt = userEntry.nextInt();
System.out.print("Please input the second number: ");
secondInt = userEntry.nextInt();
//send the numbers
output.println(firstInt);
output.println(secondInt);
answer = input.nextInt(); //getting the answer from the server
System.out.println("\nSERVER> " + answer);
} while (firstInt != 0 || secondInt != 0);
} catch (IOException e) {
e.printStackTrace();
}
catch (NoSuchElementException ne){ //This exception may be raised when the server closes connection
System.out.println("Connection closed");
}
finally {
try {
System.out.println("\n* Closing connection… *");
link.close(); //Step 4.
} catch (IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
The problem is that you mix streams and readers.
In order to successfully pass integers from client to server, for example with Data[Input/Output]Stream you should use:
// Server side
final DataInputStream InFromClient = new DataInputStream(soc_1.getInputStream());
final DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
// than use OutToClient.writeInt() and InFromClient.readInt()
// Client side
final DataInputStream FromServer = new DataInputStream(Server_info.getInputStream());
final DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
// than use ToServer.writeInt() and FromServer.readInt()
If you let's say send an int from client to server (in this case using DataOutputStream.writeInt), it is very important to read the data with the corresponding decoding logic (in our case DataInputStream.readInt).
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));
I need a bufferread to work with a client which closes when the word "CLOSE". THE client closes, I just can't get the sever to close once messages have been sent through it.
Heres what code I have:
`
import java.io.*;
import java.net.*;
class TCPClient2 {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser
= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client
DataOutputStream outToServer
= new DataOutputStream(clientSocket.getOutputStream());
InputStream sin = clientSocket.getInputStream();
// Just converting them to different streams, so that string handling becomes easier.
DataInputStream inFromServer = new DataInputStream(sin);
try {
do {
System.out.print("Enter message : ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
//Question B4
//if statement for closing the socket connection
if (sentence.equals("CLOSE")) {
clientSocket.close();
//closes client socket
System.out.println("Socket Closed");
//prints socket closed to tell user socket has closed
System.exit(0);
}
outToServer.writeBytes(sentence + '\n');
System.out.print("Message sent! please wait for server message: ");
modifiedSentence = inFromServer.readUTF();
System.out.println("FROM SERVER: " + modifiedSentence);
} while (!sentence.equals("CLOSE"));
} catch (IOException e) {
}
clientSocket.close();
}
}`
AND the server:
`
/*
chris and paul
*/
import java.io.*;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPMultiThreadServer {
private static ServerSocket welcomeSocket;
//port number the server is using
private static final int PORT = 49250;
private static int clientNo =1;
public static void main(String argv[]) throws Exception
{
System.out.println("Opening port...\n");
try
{
// ServerSocket listens for new connections on specified port
welcomeSocket = new ServerSocket(PORT);
do
{
Socket client = welcomeSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket...
TCPMultiThreadServer.ClientHandler handler =
new TCPMultiThreadServer().new ClientHandler(client,clientNo);
handler.start(); // Calls run() method in ClientHandler
clientNo++;
} while (true);
} catch (IOException e) {}
}
// Original work not credited
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader inFromClient;
private BufferedReader text_to_Client;
private DataOutputStream outToClient;
private FileWriter Filestream;
private BufferedWriter out;
public int clientNo;
public boolean stopping;
//part A question 4, adding buffer string array to the program
private String[] buffer; //creation of buffer string array.
private int bufferI; // Index of the last thing inserted into the array
public ClientHandler(Socket socket, int clientNos)
{
//Set up reference to associated socket
client = socket;
clientNo= clientNos;
try
{
// Gets access to input/output stream of socket
inFromClient =
new BufferedReader(new InputStreamReader
(client.getInputStream()));
text_to_Client =
new BufferedReader(new InputStreamReader(System.in));
outToClient =
new DataOutputStream(client.getOutputStream());
} catch(IOException e) {}
}
public void run()
{
try
{
stopping = false;
//Question A4 buffer continued
buffer = new String[4];
//generates buffer string array containing 4 strings
bufferI = 0;
// make sure bufferIndex = 0
String clientSentence;
Thread mythread = Thread.currentThread();
do
{
//Accept message from client on socket's input stream
OutputStream sout = client.getOutputStream();
// Just converting them to different streams, so that string
// handling becomes easier.
DataOutputStream text_to_send = new DataOutputStream(sout);
clientSentence = inFromClient.readLine();
System.out.println("Message received from client number " +
clientNo + ": "+ clientSentence);
// String to be scanned to find the pattern.
String line = clientSentence;
String pattern = "[C][L][O][S][E]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//if (m.find( )) {
// System.out.println("Found value: " + m.find() );
// System.out.println("Found value: " + m.group(1) );
//System.out.println("Found value: " + m.group(2) );
//} else {
// System.out.println("NO MATCH");
//}
//part B question 4 close command
//if statement for closing the socket connection if it is equal to close
if(m.matches())
{ //prints socket closed to tell user socket has closed
System.out.println("Socket connection to client number "
+ clientNo + " closed");
try
{
} catch(Exception e) {}
out.flush();
out.close(); // Close the file handler
client.close(); // Close the connection with the client,
clientNo--; // Decrement the number of clients
}
else
{
//part A question 4, adding buffer string array to the program
// looks to see if the buffer string array is full
//and also looks to see if bufferIndex is in range
if (bufferI > buffer.length-1)
{
// Print BUFFER FULL
System.out.println("BUFFER FULL");
// Clear clientSentence string
clientSentence = " ";
// For loop which travels through the buffer array of string
for (int i=0; i<buffer.length; i++)
{
// Append buffer element to clientSentence string
clientSentence += buffer[i] + " , ";
buffer[i] = null; // makes the buffer null
}
bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted
// prints buffer cleared back to the clients
text_to_send.writeUTF("BUFFER CLEARED :" +
clientSentence);
}
else
{
buffer[bufferI] = clientSentence;
System.out.println("Buffer " + bufferI+ ": " +
buffer[bufferI]);
bufferI++;
System.out.println("Enter Message: ");
// Reads message from server interface
// and sends it to the client
clientSentence = text_to_Client.readLine();
text_to_send.writeUTF(clientSentence);
System.out.println("Your message: " +
clientSentence);
}
}
if (mythread.activeCount() == 2 &&
(clientNo ==0 || clientNo >0) &&
clientSentence.equals("CLOSE"))
{
System.exit(0);
}
} while(!clientSentence.equals("CLOSE"));
client.close();
} catch(IOException e) {}
}
}
}
`