Some issues with sockets in Java - java

I'm beginning with sockets for my very first time.
I'm trying to set up a server that its only function is to give back to the client a string i send.
The client doesn't send the string, and the server doesn't receive it. Here it goes the code:
Server code:
package servidor;
//All imports needed
public class Servidor {
public static void main (String[] args){
try{
ServerSocket socketServidor = new ServerSocket(2000);
Socket socketDatos = socketServidor.accept();
PrintWriter escribirCliente = new PrintWriter(socketDatos.getOutputStream(),true);
BufferedReader leerCliente = new BufferedReader(new InputStreamReader(socketDatos.getInputStream()));
String linea;
while((linea = leerCliente.readLine())!= null){
System.out.println("hola");
System.out.println("Server: "+ linea);
escribirCliente.println(linea);
if(linea.equals("x")){
break;
}
}
socketDatos.close();
escribirCliente.close();
leerCliente.close();
socketServidor.close();
} catch (IOException e){
System.out.println("Fallo en la conexion.");
}
}
}
Client code:
package cliente;
//All imports needed
public class Cliente {
public static void main(String[] args) throws IOException{
Socket socket = new Socket("localhost", 2000);
BufferedReader leerServidor = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter escribirServidor = new PrintWriter(socket.getOutputStream());
BufferedReader teclado = new BufferedReader(new InputStreamReader(System.in));
String linea = teclado.readLine();
//System.out.println(""+linea);
while (!(linea.equals("x"))){
System.out.println("en while");
escribirServidor.println(linea);
System.out.println("eco: "+ leerServidor.readLine());
linea = teclado.readLine();
}
escribirServidor.close();
leerServidor.close();
teclado.close();
socket.close();
}
}
The thing is:
In the client, the execution never reaches the "eco" but it does reach the "en while". But in the server, that while is never reached. Not even printing the "hola". I supposed that the issue should be when reading the line, but i've been not able to fix it.
Any ideas?
Thank you in advance!

Related

Server's socket not outputting data unit client code stops running

I am playing around with networking and trying to send a simple message over my network using sockets in Java.
Here is the server code:
public class Server {
public static void main(String[] args) throws IOException {
String clientSentence;
String uppercaseSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("Server Running.");
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println("Client message received: " + clientSentence);
}
Here is the client code:
public class Client {
public static void main(String[] args) throws IOException {
String originalSentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
System.out.println("Please enter a sentence: ");
originalSentence = inFromUser.readLine();
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(originalSentence);
System.out.println("Message Sent");
}
When I run them both and input a message into the client side, there is no confirmation on the side of the server in the console, however there is confirmation on the client side that a message has been sent. If I then end the client and stop it running, the server will output the sent message to the console them immediately throw an error.
I think it has something to do with the actual BufferedReader not actually getting the message or something?
Again I am very new to networking so any help would be much appreciated
Make sure that there is symmetry in how one connection sends data and how the other side receives the data. So, if the client is sending data via a DataOutputStream, then best to read the data in as a DataInputStream. If OTOH, you're only sending Strings, I would use a Writer such as a PrintWriter and then read with a Reader. I would send each line via println(...) and would call .flush() on the PrintWriter to ensure that the buffer sends the line when desired. For example, a simple client could look like so:
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
public static final String EXIT = "exit";
public static final int HOST_ID = 6789;
public static void main(String[] args) {
// using try-with-resources so that I close all streams when done
try (
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", HOST_ID);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
) {
String input = "";
do {
System.out.print("Please enter a sentence, or \"exit\" to exit: ");
input = inFromUser.readLine();
out.println(input);
// flush the output stream to send all pending bites:
out.flush();
} while (!input.equalsIgnoreCase(EXIT));
System.out.println("All Done");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
and the Server could look like:
import java.util.*;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
// using try-with-resources so that I close all streams when done
try (
ServerSocket welcomeSocket = new ServerSocket(6789);
Scanner scanner = new Scanner(welcomeSocket.accept().getInputStream());
) {
System.out.println("Server Running.");
System.out.println("socket accepted");
while (scanner.hasNextLine()) {
String text = scanner.nextLine();
System.out.println("text: " + text);
System.out.println("uppercase: " + text.toUpperCase());
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

Echo Server doesn't echo

I'm trying to write an echo client server but I do not get any response from the server. Don't know where my mistakes are.
I've seen some examples on the internet. Some just use InputStream/OutputStream but I decided to use BufferedReader and PrintWriter - does this make any big differences?
Server side:
public class Server {
public static void main(String[] args){
Server server = new Server();
server.runServer(Integer.parseInt(args[0]));
}
private void runServer(final int port){
ServerSocket serversckt = null;
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try{
serversckt = new ServerSocket(port);
socket = serversckt.accept();
System.out.println("Request from client accepted!");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String str;
while((str = in.readLine()) != null){
System.out.println(str);
out.println(str);
out.flush();
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Client side:
public class Client{
public static void main(String[] args){
Client client = new Client();
client.runClient(Integer.parseInt(args[0]), args[1]);
}
private void runClient(final int port, final String hostname){
Socket sckt = null;
try{
sckt = new Socket(hostname, port);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
String str;
while((str = stdIn.readLine()) != null){
out.println(str);
System.out.println(in.readLine());
}
} catch(IOException e){
System.out.println(e.getMessage());
}
}
Thanks!
I'm unable to reproduce your problem. I added the missing imports and the final } in Client.java, compiled, and ran the server and client in different terminals.
Client:
$ java Client 2000 localhost
foo
foo
bar
bar
Server:
$ java Server 2000
Request from client accepted!
foo
bar
Every time I wrote something in the client window, it was echoed back to me, and the same line showed up on the server.

Java socket help debugging

I wrote a simple socket program but the sever is not printing out anything.
Client:
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 9001);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner reader = new Scanner(System.in);
while (true) {
String test = reader.next();
out.write(test);
System.out.println(test);
//String line = in.readLine();
}
}
}
Server:
public class ServerApplication {
private static final int PORT = 9001;
private static HashSet<String> names = new HashSet<String>();
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
System.out.println("Server starts!");
new ChatThread(listener.accept()).start();
}
} finally {
}
}
}
public class ChatThread extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ChatThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Thread Starts!");
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while(true){
System.out.println("Getting input!");
String input = in.readLine();
System.out.println("test");
if (input!=null){
//out.print(input);
System.out.println(input);}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any ideas how should I fix this so when I type "Hello" on client, server will print out "Hello" using system.out.println()?
This is highly likely the socket buffers not being flushed and the data is not actually sent to the socket; the server is waiting for more data before sending a chunk.
If we look at the docs for PrintWriter:
... if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked ...
However, you are using print, not println, so the flushing is not automagic.
Try manualy flushing you streams after writing data:
out.write(test);
out.flush();
yep, this was an answer to a 3 year old post... question was edited and popped up on my stream
Testing your server using telnet (telnet localhost 9001) revealed that it's working just fine. I assume that the fact that it can only print a line at a time, rather than individual characters, is intended behavior.
I did find one bug. When terminating the telnet connection, the server would go into an infinite loop. I suggest the following change:
if (input!=null){
System.out.println(input);}
}
else {
break;
}
For the client, I was able to fix it simply by replacing write with println:
out.println(test);

java: closing client socket resets server socket

I have a very simple capitalization Java program. Client sends text read from standard input to server which converts that text into capital letters. Program works well but once client is stopped (NetBeans ide used), server is also reset. Server socket should keep listening for new connection from clients regardless of a client being stopped.
public class Client
{
public static void main(String[] args) throws IOException
{
try(Socket s=new Socket("localhost",9090))
{
while(true)
{
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader rd=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader from=new BufferedReader(new InputStreamReader(System.in));
String read=from.readLine();
out.println(read);
String answer;
answer=rd.readLine();
System.out.println(answer);
}
}
}
}
public class Server
{
public static void main(String[] args) throws IOException
{
try(ServerSocket listener = new ServerSocket(9090);
Socket socket = listener.accept();)
{
while (true)
{
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Started...");
String transform=br.readLine();
String newStr=transform.toUpperCase();
out.println(newStr);
}
}
}
}
What happens is a normal behaviour. You server code only includes handling of a single client. The listener.accept() function only accepts latest connection to server. You need to put the listened.accept() in loop and handle all the exceptions that are raised within. The server-side code should look like this:
public class Server
{
public static void main(String[] args) throws IOException
{
try(ServerSocket listener = new ServerSocket(9090);
while (true) {
try {
Socket socket = listener.accept();)
…
} catch (SocketException ex) {
...
}
}
}
}
But keep in mind that this code will only handle single client at a time. No multi-threading in this code.
Your Server is closing the connection and then finishing becuase it is created outside the while loop. I believe this is what you need.
public class Server {
public static void main (final String[] args)
throws IOException {
while (true) {
try (ServerSocket listener = new ServerSocket(9090); Socket socket = listener.accept();) {
while (true) {
final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Started...");
final String transform = br.readLine();
if (transform == null)
break;
final String newStr = transform.toUpperCase();
out.println(newStr);
}
}
}
}
}

Java Server And Client Socket Need Fix

Hello, I am new to java socket programming and I was just looking to see if somebody could give me some help.
I will post the code for the client and server then i will explain my problem...
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
So my problem is even if I get rid of the loop and try to make it send the string twice it won't send it. It will only do it once unless I close and make a new socket on the client side. So if anybody could give me an explanation to what I am doing wrong that would be great, and thank you so much.
Why are you openning your outstream inside your loop?
stream = new PrintStream(socket.getOutputStream());
Take this statement outside the loop and write to your stream inside your loop.
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket:
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");
Make sure you flush the output from your server:
stream.flush();
Thanks a lot to everybody who answered but i figures out what it was all along.
i read through some of the Oracle socket stuff and figured out that the server was supposed to be the first to send a message than the client receive and send and receive... so on and so forth so i will post my new code here in hopes somebody else trying to figure out the same thing can find it with ease
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintWriter print;
public static BufferedReader reader;
public Client(String ip, int port)
{
this.ip = ip;
this.port = port;
//initiate all of objects
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 5000);
print = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//start connection with server
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
//quick method to send message
public void sendMessage(String text)
{
print.println(text);
print.flush();
try
{
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
client.sendMessage("test");
client.sendMessage("test2");
client.sendMessage("test3")
}
//Server
public static int port = 9884;
public static boolean running = true;
public static ServerSocket serverSocket;
public static Socket socket;
public static PrintWriter writer;
public static BufferedReader reader;
public static void run()
{
try
{
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("connection");
while(running)
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
writer.println(line);
writer.flush();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
run();
}

Categories