Got a server running independently.
Server code for receiving a message is as follows:
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"utf-8"));
out = new PrintWriter(clientSocket.getOutputStream(), true);
objectOut = new ObjectOutputStream(clientSocket.getOutputStream());
Sending of the message is done by this:
Socket clientSocket = new Socket("IpAddress", portNumber);
ClientConnect newConnection = new ClientConnect(clientSocket,StockMarket.getStockMarket());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "utf-8"));
BufferedReader stdln = new BufferedReader(new InputStreamReader(System.in));
while ((userInput = stdln.readLine()) != null) {
out.println(userInput);
System.out.println("INPUTED:" + userInput);
System.out.println("ECHO: " + stdln.readLine());
}
The message is received by the server fine, however it has added chars at the start. For instance if I send "HELP", it will return:
��HELP
I've read a bit into the BufferedReader and the InputStreamReader, and I've seen a few times the function: Flush. However I don't understand how to implement it or where.
A nudge in the right direction would be great.
Related
Right now, I'm trying to make a server that can display messages to the client when they connect (through localhost). When I connect through telnet, it gives me weird indentation. The code for the server is:
private ServerSocket middleman;
private int port = 8080;
private Socket client;
protected void createSocketServer()
{
try
{
while (true){
middleman = new ServerSocket(port);
client = middleman.accept();
middleman.close();
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String line;
//Client stuff
DataOutputStream dOut = new DataOutputStream(client.getOutputStream());
while((line = in.readLine()) != null)
{
System.out.println("echo: " + line);
dOut.writeByte(1);
dOut.writeUTF("Good day to you user. Here is a selection of poems " + "\n");
dOut.writeUTF("1. Cupcake Poem" + "\n");
dOut.flush();
//Response
if(line.equals("cupcake")){
try{
FileReader fileReader = new FileReader(poem);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String poemLine;
while((poemLine = bufferedReader.readLine()) != null){
stringBuffer.append(poemLine);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
//System.out.println(stringBuffer.toString());
dOut.writeUTF(stringBuffer.toString());
dOut.flush();
} catch(IOException e){
e.printStackTrace();
}
}
else{
System.out.println("wrong!, the line is:" + line);
}
}
}
}
catch(IOException e)
{
System.out.println(e);
}
}
On the client side, I'll open the command prompt and type telnet localhost 8080 then I'll type something like "fish". It will print
[?]Good day to you user. here is a selection of poems
1. Cupcake Poem
Why does it do this? If I type "cupcake" on client, it will read the file, but have weird spacing. Is this something to do with Telnet?
For telnet the correct end-of-line sequence is "\r\n". Newline by itself will only go down to the next line, but it will not back up to the first column, which what the carriage-return does.
Also note that the order matters, the telnet specifications says that it has to be "\r\n", in that order.
Also, you don't have to append the output with the newline-sequence like you do. You can write it all as a single string:
dOut.writeUTF("1. Cupcake Poem\r\n");
This client side is talking to a single threaded server. Now, what i'm trying to do is, if client#2 tries to connect to the socket while client#1 is already actively connected to the server side, to do something else. so for example,
if(socket1.gotrefused){
system.out.println("It got refused");
My code below, (It's working perfectly for me, i just want to add the above one way or another..)
Socket socket1;
int portNumber = 4445;
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
String input = br.readLine();
while ((input = br.readLine()) != null) {
if(input.equals("Hi")){
pw.println("Hello");
}
else if(input.equals("Done")){
break;
}
br.close();
pw.close();
socket1.close();
}
First I apologize for my English. I'm trying to make a Client-Server connection in Java but I have a problem getting response from the server. When I close the server first, the client will receive a response from the server. If I close the client first, nothing happens.
Here is the code of the server:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"8859_1"),1024);
DataOutputStream sendToClient= new DataOutputStream(socket.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(input.readLine());
if(sb.toString().equalsIgnoreCase("lamoyenne")) {
System.out.println(Esclave.moyenneTarif());
sendToClient.writeBytes(String.valueOf(Esclave.moyenneTarif()));
}
if(sb.toString().equalsIgnoreCase("nombrelieuentre100et200")) {
System.out.println(Esclave.nombreLieuEntre100et200());
sendToClient.writeBytes(String.valueOf(Esclave.nombreLieuEntre100et200()));
}
else {
System.out.println(Esclave.tarifParLieu(sb.toString()));
sendToClient.writeBytes(String.valueOf(Esclave.tarifParLieu(sb.toString())));
}
Here is the code for the client:
System.out.println("Type in: ");
this.connexion = new Socket(InetAddress.getLocalHost(),44000);
Writer output = new OutputStreamWriter(connexion.getOutputStream(), "8859_1");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
this.line = in.readLine();
//DataOutputStream sendToServer = new DataOutputStream(connexion.getOutputStream(),"8859_1");
//sendToServer.writeBytes(this.line+'\n');
output.write(this.line);
output.flush();
connexion.shutdownOutput();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
String temp = inFromServer.readLine();
System.out.println("FROM SERVER: "+ temp);
I have been looking through the multitudes of explanation of basic Java Socket use, and have constructed the following basic code for my own Server/Client echo pair. However, there is some hangup in the client code that I cannot find for the life of me. Perhaps someone else can spot it?
// Server Code:
try (ServerSocket serverSocket = new ServerSocket(22222);
Socket cSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(cSocket.getInputStream()))) {
System.out.println("Client connected: " + cSocket.getInetAddress().getHostAddress());
// console DOES print ^this line and correct IP when client is run.
String inLine;
while (true) {
inLine = in.readLine();
out.println(inLine);
if (inLine.equals("exit")) break;
}
// client code
try (Socket socket = new Socket("localhost", 22222);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));) {
String userIn;
while (true) {
System.out.print("Client> ");
userIn = consoleIn.readLine();
out.println(userIn); // code hangs here.
out.flush();
System.out.println("Server> " + in.readLine());
if (userIn.equals("exit")) break;
}
It isn't blocking there. It's blocking in the readLine() from the server. Try a flush() after the println() in the server.
I have a code like the one below
Server side:
Socket socket = server-client conn socket
try
{
BufferedReader inFromNode = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter outToNode = new PrintWriter(socket.getOutputStream(), true);
String data = inFromNode.readLine().toString();
String data1 = inFromNode.readLine().toString();
String data2 = inFromNode.readLine().toString();
outToNode .println("Hi");
}
Client side:
Socket socket = server-client conn socket
try
{
BufferedReader inFromNode = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter outToNode = new PrintWriter(socket.getOutputStream(), true);
outToNode .println("Hi");
outToNode .println("Hi");
outToNode .println("Hi");
String data = inFromNode.readLine().toString();
}
The problem is the client side code is waiting for the reply from the server. I am sure the server side has sent it(I tried placing logs after the send on the server side and they got printed.) Am I overlooking on something here? Is the code wrong in any way?
Try closing the PrintWriter and the Socket when writing to client finishes from Server. This should ideally fix your problem.