trying to make a simple client server chat program. I've already go it so that the server reads a user input which is then sent to the client. the client then receives this and displays it. I then have the client reading the user input and sending it to the server however the server doesn't receive it. Heres my code:
Client:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Waiting for server to respond... \n");
while (!in.ready()) {}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data2 = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data2 + "'\n");
out.print(data2);
out.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class server {
public static void main(String args[]) {
try {
System.out.println("Waiting for client connection...");
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.println("Client has connected!\n");
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data + "'\n");
out.print(data);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
while (!in.ready()) {out.close();}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
//in.close();
//out.close();
//skt.close();
//srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Both the client and the server use the same code for send/receive so I don't understand why the server won't receive.
Cheers,
Tom
print() send the text but not a new line. Try println() instead.
readLine() on the server waits for a new line, which you are not sending.
BTW: I wouldn't test for in.ready() this is more likely to be confusing than useful IMHO.
Related
I'm practising WebSocket in java and wrote two simple programs which one of them is a server that starts listening in port 9090 and receives a string as input from the client then makes a string uppercase and returns back to the client.
The program has no error but for some reason, it does not work. I can't find out what is the problem.
After debuting it seems like the server doesn't receive the inputs string even though both sides connect to each other successfully. When the user inputs his/her string the client sends it to the server but the server doesn't receive it, therefore, both programs go to the wanting stage and the application will not respond.
could you please help me with the issue?
Thanks in advance
server-side code :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
// Start listening at port 9090
ServerSocket s = new ServerSocket(9090);
System.out.println("Started: " + s);
Socket socket = s.accept();
System.out.println("conecction accepted by " + socket);
try {
// Buffer reader to get input and save it as "in"
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()
)
);
// write the output as "out"
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()
)
));
// A Loop for waiting to receive the input from the client
while (true) {
System.out.println("Watting for inpute line ...");
String line = in.readLine();
// print the input string to console to make sure it recive the input
System.out.println("inputed Line: " + line);
// sent back upper case string to client
out.println(line.toUpperCase());
out.flush();
}
}finally {
System.out.println("closing...");
socket.close();
}
}
}
The cline side code:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// get the Address for localhost
InetAddress addr = InetAddress.getByName(null);
//Connect to the server on pprt 9090
Socket s = new Socket(addr,9090);
// read and write to server using buffer reader and printwriter
try{
BufferedReader in = new BufferedReader(
new InputStreamReader(
s.getInputStream()
)
);
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream())
)
);
//Get the Ipute string from user
Scanner input = new Scanner(System.in);
while (true){
System.out.println("Enter your text:");
String line = input.nextLine();
if(line.equals("quit"))
break;
// Sent the input string to the server using 'out'
out.println(line);
// Recive the upper case string from server
String response = in.readLine();
System.out.println("Echo:... " + response);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("closing...");
s.close();
}
}
}
The server side is waiting to read a line from the client, it should work if you flush the PrintWriter on the client side:
// Sent the input string to the server using 'out'
out.println(line);
out.flush();
This is the code for my server, its supposed to take an input from the user, print it into console, then send it back to the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class DateServer {
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(10219);
Socket s = listener.accept();
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader input = new BufferedReader(in);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("connected");
out.flush();
System.out.println("connected");
String test;
while (true) {
try {
test = input.readLine();
System.out.println(test);
out.println(test + " is what I recieved");
out.flush();
} catch(Exception X) {System.out.println(X);}
}
}
}
This is the code for the client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class DateClient {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws Exception {
System.out.println("Enter IP Address of a machine that is");
System.out.println("running the date service on port 10219:");
String serverAddress = keyboard.next();
Socket s = new Socket(serverAddress, 10219);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
}
}
This was designed to work across a LAN network. I have no idea why it doesn't work, all that happens is the client will get the message "connected" and nothing else will happen, no matter what is typed into the client end. I'm a noob when it comes to java, but after a bunch of googling and searching through the java libraries, I can't seem to make it work. What did I do wrong?
You send one line from the server to the client, but in your client you wait for two lines before accepting user input to be sent to the server.
Bearing in mind that input.readLine() will block until data is received, can you spot the deadlock here:
Server:
out.println("connected");
while (true) {
try {
input.readLine();
}
}
Client:
input.readLine();
while(true) {
try {
input.readLine();
out.println(keyboard.next());
}
}
(extraneous code trimmed away to show just the problematic sequence of statements)
Both your client and server mutually wait for each other trying to do input.readLine().
This can be easily seen if you remove server's out.println("connected") and its corresponding client's first input.readLine().
On the client, you should probably write first and only then read the response. Try reordering the following lines:
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
to get
out.println(keyboard.next());
out.flush();
System.out.println(input.readLine());
In the client, try changing
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
to
PrintWriter out = new PrintWriter(s.getOutputStream());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.nextLine());
out.flush();
} catch(Exception X){System.out.println(X);}
}
Your client is trying to read two lines, but your server sends just one, then polls for input, so both are locked. Also, sinc your server is reading line-by-line, your client should be sending data line-by-line.
I am trying to set up a server with a client and a handler. The client should ask for a string from the user. This should then be written to an OutputStream, get read in by the handler which then saves the string to its own OutputStream before passing it back to the client. I know that this program is completely pointless, I am just trying to get my head around how servers, clients and handlers work.
Here is my code so far:
Server
public class Server {
public static void main (String args[]) throws IOException {
int port = 8080;
ServerSocket server = new ServerSocket(port);
while (true) {
System.out.println("Waiting for client...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected.");
Handler handler = new Handler(client);
handler.run();
}
}
}
Handler
class Handler extends Thread {
private Socket client;
public Handler(Socket c) {
client = c;
}
public void run() {
try {
Thread.sleep(3000);
System.out.println("1");
PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(client.getInputStream(),
"UTF-8"));
System.out.println("2");
String message = in.readLine();
System.out.println("4");
System.out.println("5");
out.println(message);
out.flush();
client.close();
System.out.println("Finish");
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Client
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 8080);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(server.getInputStream(),
"UTF-8"));
out.println(message);
String messageReturn = in.read();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
The problem is that the handler seems to hang when it tries to read the message in. This problem seems similar to the one presented here: Socket problem - readline won't work properly
But this solution isn't working for me. I have tried using objectInputStreams instead of my current solution, but this didn't work either.
I doubt whether your client code will compile. The return type for this is int.
String messageReturn = in.read();
Anyway, this should work:
package network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 9890);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
out.println(message);
// NOTE this
String messageReturn = in.readLine();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
Note Port has been changed.
Server Output
Waiting for client...
Client from /127.0.0.1 connected.
1
Client Output
Attempting connection...
Please enter a string:
Hello
The problem might be that you do not send an escape sequence with your response. ReadLine() waits till it gets an escape. Try sending a "\n" with your response. There is an article about problems using readLine() and println() with sockets. It also shows how to solve it.
ReadLine() / Println() and sockets
My S/W simulation of GoBack N protocol gives warning- [deprecation] readLine() in DataInputStream has been deprecated (while reading from streams) while running both client & server programs .Please tell me a solution.Is there any alternative for readLine()? Here is my client/server programs
//Server Program
import java.io.*;
import java.net.*;
import java.lang.*;
public class gobacksender
{
public static void main(String[] args)throws Exception
{
//Establishing connection
ServerSocket ss=new ServerSocket(4444);
System.out.println("Waiting for connection........");
Socket s=ss.accept();
System.out.println("Connected to client at:"+s);
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int sptr=0,sws=8,i,ano,nf,n;
String sbuf[]=new String[8];
String ch,ch1;
System.out.println("Enter the no.of frames");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter the "+nf+" messages to be send");
for(i=1;i<=nf;i++)
{
sbuf[sptr]=in.readLine();
p.println(sbuf[sptr]);
sptr=++sptr%8;
}
sws-=nf;
do
{
ano=Integer.parseInt(in.readLine());
System.out.println("Received acknowledgement for:"+ano);
System.out.println("Retransmitting...............");
for(i=ano-1;i<nf;i++)
p.println(i);
ch1=in1.readLine();
}while(ch1.equals("yes"));
sws+=nf;
}
else
{
System.out.println("the no.of frames exceed window size");
}
ano=Integer.parseInt(in1.readLine());
System.out.println("Acknowledgement received for"+ano+"frames");
s.close();
}
}
//Client Program
import java.io.*;
import java.net.*;
import java.lang.*;
public class gobackreceiver
{
public static void main(String[] args)throws Exception
{
//Connection establishment
Socket s=new Socket("localhost",4444);
System.out.println("Connected to server at:"+s);
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
String rbuf[]=new String[8];
int i,rptr=0,rws=8,nf,n;
String ch,ch1;
do
{
nf=Integer.parseInt(in1.readLine());
System.out.println("No.of messages",nf);
if(nf<rws)
{
for(i=1;i<=nf;i++)
{
rbuf[rptr]=in1.readLine();
rptr=++rptr%8;
System.out.println("The received frame"+(rptr+1)+"is:"+rbuf[rptr]);
}
rws-=nf;
do
{
System.out.println("Enter the nak number");
n=Integer.parseInt(in.readLine());
if((1<=n)&&(n<=nf))
{
p.println(n);
for(i=n;i<nf;i++)
{
rbuf[i]=in1.readLine();
System.out.println("the received frame"+i+"is;"+rbuf[i]);
}
}
else
{
System.out.println("Invalid nak");
}
System.out.println("Anymore frames lost?");
ch1=in.readLine();
p.println(ch1);
}while(ch1.equals("yes"));
System.out.println("Ack sent");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}while(ch.equals("yes"));
s.close();
}
}
Copied from the Java API Docs:
Deprecated.
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d
= new BufferedReader(new InputStreamReader(in));
If you get such warnings, your first look should always be on the API or at least googling..
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);