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);
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");
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.
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.
Here my code (sends only single String)
Client
Socket sock = new Socket("localhost",9999);
Scanner in = new Scanner(System.in);
String msg;
PrintStream pr = new PrintStream(sock.getOutputStream());
System.out.print("Enter the Msg : ");
msg = in.nextLine();
pr.print(msg);
Server
ServerSocket ser = new ServerSocket(9999);
Socket sock = ser.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String msg = br.readLine();
System.out.println("Received Msg : "+msg);
This Code Works Clearly. But I want to Send two strings through client to server.
Please help me out here... the file name is being sent, the contents of the file is also read by the client, but the contents could not be sent to the server and vice versa...
Here is the server side code...
import java.io.*;
import java.net.*;
public class Server {
public static void main(String [] args) throws Exception{
ServerSocket s_sock = new ServerSocket(4567);
System.out.println("Server ready for connection...");
Socket c_sock = s_sock.accept();
System.out.println("Connection established ...server listening...");
// reading the filename from client
InputStream is1 = c_sock.getInputStream();
BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
String f_name1 = br1.readLine();
System.out.println("File sent from client is :" + f_name1);
// receiving file contents from client and copying
String contents1 = null;
InputStream is2 = c_sock.getInputStream();
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
FileWriter fw1 = new FileWriter("from_Client.txt");
BufferedWriter bw1 = new BufferedWriter(fw1);
while((contents1= br2.readLine()) != null) {
bw1.write(contents1);
}
System.out.println("File copied successfully");
// reading the filename from client and sending contents to client
InputStream is3 = c_sock.getInputStream();
BufferedReader br3 = new BufferedReader(new InputStreamReader(is3));
String f_name2 = br3.readLine();
System.out.println("File required by client is :" + f_name2);
String contents2 = null;
FileReader fr2 = new FileReader(f_name2);
BufferedReader br4 = new BufferedReader(fr2);
OutputStream os1 = c_sock.getOutputStream();
PrintWriter pw1 = new PrintWriter(os1, true);
while((contents2 = br4.readLine()) != null) {
pw1.println(contents2);
}
}
}
and here is the client side code
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws Exception {
Socket c_sock = new Socket("127.0.0.1", 4567);
//specify file name to send to server
System.out.print("Enter the file name to upload to the server:"+"\t");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String f_name1 = br1.readLine();
OutputStream os1 = c_sock.getOutputStream();
PrintWriter pw1 = new PrintWriter(os1, true);
pw1.println(f_name1);
//sending file contents to server
String contents1 = null;
FileReader fr1 = new FileReader(f_name1);
BufferedReader br2 = new BufferedReader(fr1);
OutputStream os2 = c_sock.getOutputStream();
PrintWriter pw2 = new PrintWriter(os2, true);
while((contents1 = br2.readLine()) != null) {
pw2.println(contents1);
}
//specify file name to send to server
System.out.println();
System.out.print("Now enter the file name to download from server:"+"\t");
BufferedReader br3 = new BufferedReader(new InputStreamReader(System.in));
String f_name2 = br3.readLine();
OutputStream os3 = c_sock.getOutputStream();
PrintWriter pw3 = new PrintWriter(os3, true);
pw3.println(f_name2);
// receiving file contents from server and copying
String contents2 = null;
InputStream is1 = c_sock.getInputStream();
BufferedReader br4 = new BufferedReader(new InputStreamReader(is1));
FileWriter fw1 = new FileWriter("from_Server.txt");
BufferedWriter bw1 = new BufferedWriter(fw1);
while((contents2 = br4.readLine()) != null) {
bw1.write(contents2);
}
System.out.println("File copied successfully");
}
}
Get rid of the second BufferedReader and use the first for everything. They are stealing data from each other.
Same applies at the client, and also to the two PrintWriters.
Of course the entire approach will only work for text files. If you send binary files through this code, they will be corrupted by the char conversions.