Unable to get message from client in client-server program in java - java

I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.

In the client replace:
output.println(line.getBytes());
with
output.println(line);

Related

read write from server and client both side in eclipse

I've the code for server and client classes. I've two classes, ServerApp working as server and ClientApp working as client in my local machine.
I first run the ServerApp class and then the ClientApp class. After running the ClientApp class I write some message in the eclipse console "Hello Server" then the message is printed in ServerApp console displaying the client message.
But when I run the ServerApp class and write some text in console and running the ClientApp does not display any message in the console.
I can not understand how to show two way message communication in eclipse console? Please suggest how I can perform two way communication (client server) in eclipse.
Server App
import java.io.*;
import java.net.*;
public class ServerApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket Server_Socket;
Server_Socket = new ServerSocket(5555);
Socket clientSocket = null;
clientSocket = Server_Socket.accept();
DataInputStream input;
input = new DataInputStream(clientSocket.getInputStream());
System.out.println(input.readUTF());
DataOutputStream output;
output = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop"))
{
str = input.readUTF();
System.out.println("client says: " + str);
str2 = br.readLine();
output.writeUTF(str2);
output.flush();
}
input.close();
clientSocket.close();
Server_Socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Client App
import java.io.*;
import java.net.*;
public class ClientApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket Client_Socket;
Client_Socket = new Socket("localhost", 5555);
DataInputStream input;
input = new DataInputStream(Client_Socket.getInputStream());
DataOutputStream output;
output = new DataOutputStream(Client_Socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "", str2 = "";
while (!str.equals("stop")) {
str = br.readLine();
output.writeUTF(str);
output.flush();
str2 = input.readUTF();
System.out.println("Server says: " + str2);
}
output.flush();
output.close();
Client_Socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Server, Client socket implementation

Am writing a Server, client chat program using Java Socket. Here is my code for the Server socket class.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine();
output.println(inputLine);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
The client is able to make a connection and send a message to the server. The server can also receive the messages sent by the client. The problem is that when the message is sent from the server, the client does not receive the message. Here is my client socket code.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) throws Exception
{
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true)
{
System.out.println("Client: ");
line = clientInput.readLine();
output.println("Server: " + line );
if(line.equals("quit"))
{
break;
}
}
}
input.close();
clientInput.close();
output.close();
}
}
Server side:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println("Client request: " + inputLine);
String resp = "some response as you need";
output.println(resp);
System.out.println("Server response: " + resp);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
Client side:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String inputStr = clientInput.readLine();
output.println(inputStr);
System.out.println("Client: " + inputStr);
if (inputStr.equals("quit")) {
break;
}
String serverResp = input.readLine();
output.println("Server: " + serverResp);
}
}
}
}
It is tested.
It's always a good idea to flush your output streams when you are done with them, the info you are sending may have buffered.
The server is expecting an extra line from the client input here:
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine(); // <--- here
The client is not reading from the InputStream called input it gets when it connects to the server. It is only reading the local console input from clientInput.
In the while loop in Client.java you need something like this after the quit block to get the server's response:
System.out.println("Server: " + input.readLine());

Threads/Sockets in a client server mini application

I basically try to make a simple domain resolver using sockets.
I am pretty far and I its working how it is now. Except my main function where I try to make a thread which keeps listening and waiting for another call. After I type www.google.com it gives me the address but when I try it again, it does nothing. I think the socket closes or something. I wanted to use threads and while loops but I'm struggling with this problem for hours.
Client side ( EchoClient.java )
package tetst222;
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
try
{
Socket sock = new Socket("localhost", 1350);
PrintWriter printout = new PrintWriter(sock.getOutputStream(),true);
InputStream in = sock.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bin.readLine()) != null)
{
System.out.println(line);
}
//sock.close();
}
catch(IOException ioe)
{
System.err.println(ioe);
}
}
}
And this code:
Server side ( EchoServer.java )
package tetst222;
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class EchoServer //implements Runnable
{
public static void main(String[] args) throws IOException
{
try
{
ServerSocket sock = new ServerSocket(1350);
while(true)
{
// open socket
Socket client = sock.accept();
PrintWriter printout = new PrintWriter(client.getOutputStream(),true);
printout.println("Je bent succesvol verbonden met de host");
printout.println("Geef een hostnaam op waarvan je het IP-adres wilt achterhalen:");
//get input from client
InputStream in = client.getInputStream();
BufferedReader bufin = new BufferedReader(new InputStreamReader(System.in));
/*
Thread t = new Thread();
t.start();
*/
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
client.close();
}
}catch(IOException ioe)
{
System.err.println(ioe);
}
}
/*
public void run() {
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
}
*/
}
Your server don't handle client requests. It wait for new client (socket.accept) and read default system input (System.in) not a socket, and after just close client connection.
it look like:
public static void main(String[] args) throws IOException {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
String host = sc.nextLine();
try {
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
} catch (UnknownHostException uhe) {
System.out.println(uhe.toString());
}
}
}
At the client side you should read address from console, write it to socket (send request), then read data from socket (take response) and out to console;
At the server side you must accept client connection (socket.accept), read data from socket (take request), handle it (InetAddress.getByName(host)) and send response back to the client socket.

While loop fails when socket reading input in java

so I am having an issue with reading input from a client. It works completely fine whenever I am using my if statements without the while statements wrapped around it in the server class. Could anybody point me to why this may be failing?
Server class:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
//When this while is here. The match fails and it goes to the else statement.
//Without the while statement it will work and print "Received our hello message."
//when the client says HELLO.
while(message != null)
{
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
}
}
Client class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
System.out.println(message);
}
}
You're never modifying message inside the while loop so you have an infinite loop.
Try
while((message = br.readLine()) != null)
You only loops at the Server side, while u forgot to loop at the Client side, I did a quick fix for you, and also help you closed your connections.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message;
//= br.readLine();
//Confirms that the message was received
//When this while is here. The match fails and it goes to the else statement.
//Without the while statement it will work and print "Received our hello message."
//when the client says HELLO.
PrintStream ps = new PrintStream(socket.getOutputStream());
while((message =br.readLine())!=null)
{
System.out.println(message);
if(message.equals("HELLO"))
{
ps.println("Received our hello message.");
}
if(message.equals("END"))
{
ps.println("Client ended the connection");
break;
}
else
{
ps.println("Did not receive your hello message");
}
}
ps.close();
br.close();
ir.close();
serverSocket.close();
}
}
Client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage ="";
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
while(!(cMessage.trim().equals("END"))){
cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
String message = br.readLine().trim();
System.out.println(message);
}
br.close();
ir.close();
scan.close();
ps.close();
clientSocket.close();
}
}
Your code is working just fine for sending one 'HELLO' message.
However, like ^Tyler pointed out, If you want to keep sending messages you need to move 'while((message = br.readLine()) != null)' in the while loop.
Using a loop like you are...
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
sleep(in);
if(!in.ready()){
break;
}
}
There is a cheater way that I figured out.
private static void sleep(BufferedReader in) throws IOException {
long time = System.currentTimeMillis();
while(System.currentTimeMillis()-time < 1000){
if(in.ready()){
break;
}
}
}
This might be sloppy, but if you make a sleep method that waits an amount of time and just keep checking if the BufferedReader is "ready." If it is, you can break out, but then when you come out check again. -- Maybe you could just return a boolean instead of checking twice, but the concept is there.

Simple Client Server Application, but something is going wrong

I am using Socket and ServerSocket classes to communicate on local host
client sends a no. to server and server computes square of no. and sends back to the client
// Client Class
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("127.0.0.1",10101);
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
// Server Side
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(10101);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}
Please Help
On client side do this after sending data to server
pw.println(i);
pw.flush();

Categories

Resources