Can not read from socket using BufferedReader.readline() - java

I am trying to develop a client/Server communication application in java. But at the very initial stage I am unable to read data string from the socket's Output stream using BufferedReader.readline(). I have googled a lot but could not find the specific answer to my question.Debugging the client application shows that the client application halts at response.readline().
Server:
package myserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyServer {
public static void main(String[] args) {
String[] tokens = new String[10];
int count = 0;
ServerSocket server = null;
try {
server = new ServerSocket(16);
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
if (server != null) {
while (true) {
PrintWriter response;
BufferedReader command;
String inCommand;
try {
Socket client = server.accept();
System.out.println("Connected!");
response = new PrintWriter(client.getOutputStream());
command = new BufferedReader(new InputStreamReader(client.getInputStream()));
response.print("EHLO\r\n");
command.read(); //just to stop the application to start a new iteration
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Client:
package myclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyClient {
public static void main(String[] args) {
Socket server = null;
PrintWriter command;
BufferedReader response;
BufferedReader Console = new BufferedReader(new InputStreamReader(System.in));
try {
server = new Socket("175.107.231.218", 16);
System.out.println("Connected");
command = new PrintWriter(server.getOutputStream());
response = new BufferedReader(new InputStreamReader(server.getInputStream()));
while (server.isBound()) {
String input = response.readLine(); //Here is where the communication halts
System.out.print(input);
}
} catch (UnknownHostException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Any idea about this issue?

You may need to call response.flush() from the server to ensure that the socket does not buffer your message waiting for more writes to batch together.

Related

How do i establish communication between socket threads of server in order to communicate between clients?

so i'm trying to create a chess server for a chess application i wrote in java. The two classes i'm including are the main class that starts my TCPServerThreads and this class itselve.
I am able to connect two clients and for example echo their input back to them, but i have no idea, how to exchange information between these two threads. I am trying to forward Server inputs from one client towards the main class, or directly to the other client, so i can update the chess field on the client.
It's pretty much my first time working with servers, so thanks in advance for you patience.
This is my main class:
package Main;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import TCP.TCPServerThread;
public class Main {
public static final String StopCode = "STOP";
public static final int PORT = 8888;
public static int count = 0;
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
//create Server Socket
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("serverSocket created");
//accept client Sockets
while (count < 2) {
try {
socket = serverSocket.accept();
count ++;
System.out.println("socket Nr " + count + " accepted");
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new TCPServerThread(socket).start();
}
}
}
And this is the TCPServerThread:
package TCP;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import Main.Main;
public class TCPServerThread extends Thread{
Timestamp ts;
private int port = 0;
Socket socket;
public TCPServerThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
InputStream is = null;
BufferedReader br = null;
DataOutputStream os = null;
try {
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
os = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
String line;
while (true) {
try {
line = br.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
if(line.equalsIgnoreCase("sp") && this.activeCount() == 3) {
os.writeBytes("1" + "\n\r");
os.flush();
}
os.writeBytes("Echo reply: " + line + "\n\r");
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
Thank you very much! I made the tcp threads implement runnable instead of extend thread. Then i added a ConnectionManager between the main and the TCPThreads which isn't static. This way i can put the manager into the TCPThreads constructor and communicate between its objects.

Java - Multi-Threaded Socket Server, How to check a clients connection to the server?

I am wondering how to check if a client is still connected to a server, like to see if the client has crashed, and if not, to check its ping to the server. Im adding all new clients to an ArrayList and when they crash I want to know how to remove them from the list so that I can keep things clean. Im not sure how to do this with Synchronization or if thats possible. If there is a better way too control my threads any advice is welcomed, thanks.
SERVER CODE:
package Main;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MultiThreadedServer implements Runnable{
private static List<Thread> clients = new ArrayList<Thread>();
Socket cs;
private static ServerSocket ss;
private static int port = 25570;
MultiThreadedServer(Socket cs){
this.cs = cs;
}
public static void main(String args[]) throws Exception{
try{
ss = new ServerSocket(port);
System.out.println("Server Listening");
}catch(IOException e){
System.out.println("Port Taken");
}
while(true){
Socket newClient = ss.accept();
System.out.println(newClient.getInetAddress() + " Has Connected");
Thread client = new Thread(new MultiThreadedServer(newClient));
client.start();
clients.add(client);
System.out.println("Connected Clients: " + clients.size());
}
}
public void run(){
try{
PrintStream ps = new PrintStream(cs.getOutputStream());
ps.println("Welcome Client #" + clients.size());
}catch(IOException e){
System.out.println(e);
}
}
}
CLIENT CODE:
package Main;
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.net.UnknownHostException;
public class Client{
private static String ip = "127.0.0.1";
private static int port = 25570;
public static void main(){
Socket socket;
BufferedReader reader;
PrintWriter writer;
try {
socket = new Socket(ip,port);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
OutputStreamWriter os = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter out = new PrintWriter(os);
System.out.println(in.readLine());
} catch (UnknownHostException e) {
System.out.println("ERROR UNKNOWN");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not connect to server!");
e.printStackTrace();
return;
}
}
}

Connect App with Server

I have created two Java programs, a server and a client which can communicate with each other, if they're executed on the same PC.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try {
server = new ServerSocket(5555);
System.out.println("Server gestartet!");
while(true){
try {
Socket client = server.accept();
//Thread t = new Thread(new Handler(client));
//t.start();
executor.execute(new Handler(client));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Handler (Server creates each time an instance when a new client joins):
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Handler implements Runnable {
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try{
//Streams
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// ------------------------------
String s = null;
while((s = reader.readLine()) != null){
writer.write(s + "\n");
writer.flush();
System.out.println("Empfangen vom Client: " + s);
}
writer.close();
reader.close();
client.close();
}catch(Exception e){}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket client = new Socket("localhost", 5555);
System.out.println("Client gestartet!");
//Streams
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// ------------------------------
writer.write("Hallo Server!\n");
writer.flush();
String s = null;
while((s = reader.readLine()) != null){
System.out.println("Empfangen vom Server: " + s);
}
reader.close();
writer.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My question now is:
How can make a server on my computer which can be accessed via Internet? My first thougt was to change something in the constructor of the client socket
Socket client = new Socket("localhost", 5555);
"localhost" probably means that the server runs on the same PC as the client.
My goal would be to have an app on my smartphone which connects via Internet to my server which runs on my PC. It should send back my message I entered.
Get your public IP address using http://whatismyip.com
Change the client code to Socket client = new Socket("<replace_with_your_public_ip>", 5555);
Make sure the client is allowed to open outgoing connections to port 5555 (this is usually the case if connected in Wifi, but not if you are using 3G/4G)
Configure the router to which your server is connected, so that it redirects incoming connections from the Internet on port 5555 to the IP of your server on the LAN (still on port 5555). This kind of settings usually can be found in a section called "NAT", in the router admin console (usually accessible via http://192.168.0.1 or http://192.168.1.1 depending on the router model).

Java TCP Client Server Hangs Up?

I am currently having difficulty understanding why my code is not working. I've included my client and server code below. I've figured out that my problem happens somewhere in the while loops but I'm not sure how to fix it so that it doesn't get stuck. I've searched around the forum for a while and some said adding a newline character would fix it, but I'm still having trouble.
My main question is how can I avoid the process from getting stuck and not communicating properly. Can anybody out there point me in the right direction?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print('\n');
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
-----------------------------------------------------------------
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print('\n');
}
System.out.println("Client disconnected");
r.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Both ends are reading until EOS and neither is closing until after that. So you have a classic deadlock. You need to rethink your application protocol.
You also need to tell your PrintStream or PrintWriter to autoflush, or else call flush() yourself, but this is a relatively minor matter compared to the mistake above.
You should use autoflush on your PrintWriters like this:
PrintStream w = new PrintStream(cs.getOutputStream(),true);
You can setup a PROTOCOL to end the communication something like this:
In your client:
w.println("[END]");
In your server:
while (!(line = r.readLine()).equals("[END]")) {
Hope this helps:
Check the comments
And be sure that you get Client Connected on console of server side
CLIENT SIDE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print("\n"); // enter new line
w.flush();// flush the outputstream
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
SERVER SIDE
----------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print("\n");// entering new line
}
System.out.println("Client disconnected");
r.close();
w.close();// close w
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

server make a txt file and client write it

I have a project that has a server which creates an empty text file.
Once my client stops writing to this file, the server should read and display the results.
My problem is that the client is connecting to the server, but whatever text the client is sending is not being written on the server side. In addition, when I exit, the server doesn't quit.
This is what I have so far:
The Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readUTF();
os.println(line);
os.flush();
out.write(line);
out.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Here is my client:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null && is != null) {
try {
do{
System.out.print("Write what the client will send: ");
strout = in.nextLine();
os.writeBytes(strout);}
while(!strout.equals("exit"));
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
};
Try this.
In your server
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
if( line != null ){
out.write(line + '\n');
out.flush();
}
}
}
And about the 'exit' part of your client try after changing
while(!strout.equals("exit"));
to
while(!strout.equalsIgnoreCase("exit"));
Hope this helps !!
Today my teacher is upload a new project because he has make a false , the project i have to make is similar which the old but the client is reading or writing a txt with number from 0-911, The client is choice randomly what is make read o write if choice read show the numbers of txt if choice write he write randomly a number from 0-911 and stop if choice the 100.
i make it but nothing show me is stack.
sever
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
int line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
boolean ch=true;
{
line =(Integer) br.read();
// System.out.println(line);
os.println(line);
os.flush();
out.write(line+"\n");
out.flush();
} while (line != 100);
os.close();
out.close();
br.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
client
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
int number=0;
Random rand = new Random(System.currentTimeMillis());
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost");
}
int choice=2;//rand.nextInt(2);
if(choice==1){
int num=is.read();
System.out.println(num);
}
else if(choice==2){
try {
do{
number=rand.nextInt(911);
// System.out.println(number);
os.writeInt(number);
}while(number!=100);
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}

Categories