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();
}
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.
So I want to read from socket , but it doesn't gives me anything , I am newbie to java networking so please help me , it doesn't gives me any errors but doesn't gives me any output from client socket too... here is a source code:
ServerSocket server = new ServerSocket(4444);
Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputline = in.readLine();
while(inputline != null)
{
System.out.println("recieved "+inputline);
}
out.close();
in.close();
server.close();
client.close();
You call readLine() exactly once. If it's not null on the first iteration, you've got an infinite loop (because it will forever be non-null). Be sure to update it.
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 to write server application that request questions from client and receives an answer. This is my client code:
clientSocket = new Socket("localhost", 1234);
System.err.println("Client started");
//get questions
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Question q = (Question)in.readObject();
//send answer
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
out.print("a1");
out.flush();
and server code:
//sending questions
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
List<Question> quest = Questions.getInstance().getQuestions();
out.writeObject(quest.get(0));
out.flush();
//get answer
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String temp = null;
while ((temp = in.readLine()) == null) {}
String answer = temp;
Questions successfully sent and later received by client, but server never get answer (infinite loop while reading temp variable). What is the problem?
Your calling out.print("a1"); on the client, but reading a line on the server using in.readLine(). Shouldn't you be writing out using println() on the client, else the server never gets to the end of the line? – CodeChimp Nov 21 at 21:07
Thanks for CodeChimp