Java, Sockets, BufferedReader and StringBuilder - java

Yestarday I wrote a post about Java and Sockets, and today I'm still here because I'm having an issue with BufferedReaders.
I searched some questions here in StackOverflow and I understand the problem, but I can't fix it
My "application" has got two parts: a server and a client, and the scope of the application is to execute MS-DOS commands on the machine where the server is running (the commands are sent by the client).
Now the code (I will post the total code because it's easier to understand, I will put a comment in non-working part of the code) Server:
import java.net.*;
import java.io.*;
public class TCPCmdServer {
public int port;
public ServerSocket server;
public final String version = "Beta 1.0";
TCPCmdServer(int port) {
this.port = port;
if (!createServer())
System.out.println("Cannot start the server");
else {
System.out.println("**********************************************");
System.out.println("Command executer, server version: " + version);
System.out.println("Server running on port " + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createServer() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdServer tcp = new TCPCmdServer(5000);
while (true) {
Socket socket = null;
BufferedReader in = null;
BufferedWriter out = null;
try {
socket = tcp.server.accept();
System.out.println("A client has connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close the connection\n");
out.flush();
} catch (IOException exc) {
exc.printStackTrace();
}
if (socket != null && in != null && out != null) {
try {
String cmd = null;
while (!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder builder = new StringBuilder();
while ((line = pRead.readLine()) != null) {
builder = builder.append(line + "\n");
}
out.write(builder.toString() + "\n");
//here is sent "EnD"
out.write("EnD \n");
out.flush();
System.out.println(builder.toString());
pRead.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Closing connection...");
try {
socket.close();
in.close();
out.close();
} catch (IOException excp) {
excp.printStackTrace();
}
}
}
}
}
}
And now the code for the client part
import java.net.*;
import java.io.*;
public class TCPCmdClient {
public Socket socket;
public int port;
public String ip;
public final String version = "Beta 1.0";
TCPCmdClient(String ip, int port) {
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else {
System.out.println("**********************************************");
System.out.println("Command executer, client version: " + version);
System.out.println("Connected to " + ip + ":" + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createSocket() {
try {
socket = new Socket(ip, port);
} catch (IOException e) {
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try {
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag) {
System.out.println("Type a command... type END to close the connection");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END")) {
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else {
//The loop doesn't finish because the reader
//listens for a new line
//so I used the string "EnD", sent by the server to
//stop the loop, anyway it doesn't seem to work
//I put a comment in the server where "EnD" is sent
String output;
while (((output = in.readLine()) != null)) {
if (output.equals("EnD")) {
break;
} else {
System.out.println(output);
}
}
System.out.println(" *************************************** ");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The problem is that the BufferedReader waits for a new line forever in the while loop (I wrote a comment in the code). I tryed to stop it using a "special string", but it doesn't seem to work.
I can't change the while in
String output;
while (((output = in.readLine()) != null) && output.length > 0)
{
//code here...
}
because in the output of the MS-DOS command (think on "ipconfig") are also present empty lines.
How could I correct it?
Thank you for your help!

your client Sends "EnD " (with a whitespace at the end) and you are comparing to "EnD" without a whitespace. So the two strings are not equal. try to send it without the white space:
out.write("EnD\n");

Space is missing. In TCPCmdClient.java change
if (output.equals("EnD")) {
to
if (output.equals("EnD ")) {

Related

Java BufferedReader frozen [duplicate]

I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
My Client:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.
you should add "\r\n" at the end of the String which write into stream.
example:
client :
string = "end";
out.write(string + "\r\n");
out.flush();
server :
out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;
I don't see the server response.
You do a
System.out.println("br: " + string);
but not a
out.write(string);
out.flush();
Appand "\n" to end of the response from server.
outToClient.writeBytes(sb.toString() + "\n");
You are reading lines but you aren't writing lines. Add a newline, or call BufferedReader.newLine().

Python Socket Only get information when the socket is closed

I am creating a program to play chess through the socket. My client is written in Python which is using socket to send data to the server. I receive information only when client program gets closed. Below mentioned is the client code. I am using python socket https://docs.python.org/3/library/socket.html
def youSecond(board):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.11.46', 9999))
run = True
turn = 1
new_msg = True
while run:
renderMap(board)
move = s.recv(1024).decode("utf-8")
if new_msg:
new_msg = False
print("SERVER: ", move)
players[0].play(board, move)
new_msg = True
turn +=1
renderMap(board)
print("Black machine is thinking.....")
myTurn = players[1].play(board, turn).encode("utf-8")
s.send(myTurn)
turn += 1
and my server using Java
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;
public ClientHandler(Socket clientSocket, PrintWriter user) {
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
System.out.println("tren helllo");
} catch (Exception ex) {
ta_chat.append("Unexpected error... \n");
}
}
#Override
public void run() {
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat";
String[] data;
try {
while ((message = reader.readLine()) != null) {
System.out.println("duoi helllo");
ta_chat.append("Received: " + message + "\n");
data = message.split(":");
for (String token : data) {
ta_chat.append(token + "\n");
}
if (data[2].equals(connect)) {
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
try {
FileWriter fw = new FileWriter("C:\\Users\\Admin\\Desktop\\FixCoTuong\\moves.txt");
fw.write(data[1]);
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("sucess");
} else {
ta_chat.append("No Conditions were met. \n");
}
}
} catch (Exception ex) {
ta_chat.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
}

Multithreading with client server program

I am trying to implement multi threading with a client/server program I have been working on. I need to allow multiple clients to connect to the server at the same time. I currently have 4 classes: a Client, a Server, a Protocol and a Worker to handle the threads. The following code is what I have for those classes:
SocketServer Class:
public class SocketServer {
public static void main(String[] args) throws IOException {
int portNumber = 9987;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
Thread thread = new Thread(new ClientWorker(clientSocket));
thread.start(); //start thread
String inputLine, outputLine;
// Initiate conversation with client
Protocol prot = new Protocol();
outputLine = prot.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = prot.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("quit"))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
SocketClient Class:
public class SocketClient {
public static void main(String[] args) throws IOException
{
String hostName = "localhost";
int portNumber = 9987;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("quit"))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Protocol Class:
public class Protocol {
private static final int waiting = 0;
private static final int sentPrompt = 1;
private int status = waiting;
public String processInput(String theInput) {
String theOutput = null;
if (status == waiting) {
theOutput = "Please enter what you would like to retrieve: 'customer' or 'product' ";
status = sentPrompt;
}
else if ( status == sentPrompt ) {
if ( theInput.equalsIgnoreCase("product")) {
File f = new File("product.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current product entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("customer")) {
File f = new File("customer.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current customer entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("quit")) {
return "quit";
}
else {
return "quit";
}
}
return theOutput;
}
}
The ClientWorker Class:
public class ClientWorker implements Runnable {
private final Socket client;
public ClientWorker( Socket client ) {
this.client = client;
}
#Override
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
System.out.println("Thread started with name:"+Thread.currentThread().getName());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
System.out.println("Thread running with name:"+Thread.currentThread().getName());
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
When I run the server and client, everything works fine as expected. Then when I try to run another client, it just hangs there and does not prompt the client to give a response. Any insight into what I am missing is greatly appreciated!
Your server code should address implement below functionalities.
Keep accepting socket from ServerSocket in a while loop
Create new thread after accept() call by passing client socket i.e Socket
Do IO processing in client socket thread e.g ClientWorker in your case.
Have a look at this article
Your code should be
ServerSocket serverSocket = new ServerSocket(portNumber);
while(true){
try{
Socket clientSocket = serverSocket.accept();
Thread thread = new ClientWorker(clientSocket);
thread.start(); //start thread
}catch(Exception err){
err.printStackTrace();
}
}
How many times does serverSocket.accept() get called?
Once.
That's how many clients it will handle.
Subsequent clients trying to contact will not have anybody listening to receive them.
To handle more clients, you need to call serverSocket.accept() in a loop.

Client server programming in java with options to user

My task is to display three options to the user 1)connect to server 2)post data 3)disconnect. I am having trouble in sending the file to the server. "The file needs to be sent from client to server". I am new to socket programming and however I try the connection is being reset while I try to send the file to server.
server
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
boolean flag = true;
while (flag) {
try {
System.out.println("Waiting for client on port "
+ serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
Scanner reader = new Scanner(server.getInputStream());
File file = new File("compile.txt");
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(
file));
while (reader.hasNextLine()) {
String str = reader.next();
fileWriter.write(str);
System.out.println("" + str);
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 4444;
try {
Thread t = new Server(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Client {
public static void main(String[] args) {
Socket client = null;
boolean flag = true;
while (flag) {
System.out
.println("Please enter your choice\n1.Connect to Server\n2.Post Data\n3.Disconnect from Server");
Scanner userChoice = new Scanner(System.in);
int choice = userChoice.nextInt();
String serverName = "localhost";
int port = 4444;
if (choice == 1) {
try {
System.out.println("Connecting to " + serverName
+ " on port " + port);
client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
} else if (choice == 2) {
System.out.println("enter path of file to be compiled");
Scanner pathReader = new Scanner(System.in);
String path = pathReader.next();
pathReader.close();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
PrintWriter writer = new PrintWriter(
client.getOutputStream(), true);
writer.write(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
client.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (choice == 3) {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
System.out.println("enter a valid input");
}
}
}
First of all client-server socket connections and applications are pretty complicated. I'd recommend reading:
http://www.oracle.com/technetwork/java/socket-140484.html#sockets
couple of things to consider:
make sure there is nothing running on the socket.
make sure that the server is listening
You are running the server on one thread, so if it finishes at all then it won't restart
You are not closing the fileWriter once you have finished writing -
please post your output/any stacktraces you have

Console based login application using java sockets

I am making a console based java application - which will check the username and password of client. What I want is the data entered by client must enter to server in a line by line format i.e pressing enter must send username data and password for next enter press. But what the problem is - until I quit at the client side the data is not sent to the server. Meaning , when client hits 'Bye.' then the client is closed and server receives the data then. Help me in this regard as this is the first step - later I have to check database with this username and password on server. My codes are as follows :
Server :
import java.net.*;
import java.io.*;
public class EchoServer2 extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2010);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
PrintWriter out1 = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
BufferedReader in1 = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine,u,p;
while ((u = in.readLine()) != null && (p = in.readLine()) != null)
{
System.out.println ("U: " + u);
out1.println(u);
System.out.println ("P: " + p);
out1.println(p);
if (u.equals("Bye."))
break;
}
out1.close();
out.close();
//in1.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client :
import java.io.*;
import java.net.*;
import java.lang.*;
import java.io.Console;
public class EchoClient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port .");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader in1 = null;
try {
echoSocket = new Socket(serverHostname, 2010);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader std = new BufferedReader(
new InputStreamReader(System.in));
String upwd,uname,text;
Console console = System.console();
String username = console.readLine("Username:");
char[] pwd = console.readPassword("Password:");
upwd=new String(pwd);
while (username!=null && upwd!=null && (uname = stdIn.readLine()) != null)
{
out.println("Username:"+username);
out.println("Password:"+upwd);
// end loop
if (uname.equals("Bye."))
break;
}
out.close();
stdIn.close();
echoSocket.close();
}
}
On the client side, do out.flush() after writing the password to the stream.

Categories