Client Application not receiving String output from the Server Application - java

I intend to have server application to send String object to the client
application, and have it print out what was sent, until what was sent from
server equals to "stop".
The source below is the Server application,
/*
Server application
*/
import java.util.*;
import java.io.*;
import java.net.*;
class FunServer{
public static void main(String args[])throws Exception
{
ServerSocket ss = new ServerSocket(1234);
Socket link = ss.accept();
System.out.println("Connection has been established");
//Read
Scanner reader = new Scanner(link.getInputStream());
//Write
PrintWriter writer = new PrintWriter(link.getOutputStream());
Scanner keyboard = new Scanner(System.in);
String send;
while(true){
System.out.println("Please, enter your input.");
send = keyboard.nextLine();
if(send.equalsIgnoreCase("stop")){
break;
}
wrter.println(send);
}
link.close();
}
}
and the source below is the client application.
import java.util.*;
import java.io.*;
import java.net.*;
class FunClient{
public static void main(String args[])throws Exception
{
String output;
InetAddress local = InetAddress.getLocalHost();
Socket link = new Socket(local, 1234);
System.out.println("Connection Successful.");
Scanner reader = new Scanner(link.getInputStream());
PrintWriter writer = new PrintWriter(link.getOutputStream());
while(true){
output = writer.nextLine();
if(output.equals("close")){
break;
}
System.out.println(output);
}
link.close();
}
}
After the user inputs a valid String, nothing is printed out in the client
application.
Am I using the Scanner and the PrintWriter in a wrong manner?
Thank you.

Related

Trouble with simple java socket and thread program

I'm trying to learn how to use threads alongside sockets in java. I have a very simple program. Its function is to have the user input a string and to have that message received and printed out by the server whose socket is running inside of a thread. I get it to print out "Connection established!" and to accept inputs from the user, but they never seem to print out. Is there some reason why received messages aren't being printed to the console?
Here is the Client class:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
InetAddress host = InetAddress.getLocalHost();
TCPServer newServer = new TCPServer(5001);
Thread thread = new Thread(newServer);
thread.start();
Socket socket = new Socket(host,5001);
String outgoing_message = "";
Scanner scan = new Scanner(System.in);
PrintWriter printer = new PrintWriter(socket.getOutputStream());
while(!outgoing_message.equals("close")) {
System.out.print("Enter message: ");
outgoing_message = scan.nextLine();
printer.println(outgoing_message);
}
socket.close();
}
}
And here is the TCPServer class:
package Package_Two;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPServer implements Runnable{
private Socket socket;
private ServerSocket serverSocket;
public TCPServer(int port) throws IOException{
this.serverSocket = new ServerSocket(port);
}
#Override
public void run(){
try {
this.socket = serverSocket.accept();
System.out.println("Connection established!");
Scanner scan = new Scanner(socket.getInputStream());
String incoming_message = "";
while(!incoming_message.equals("close")){
incoming_message = scan.nextLine();
System.out.println("Received message: " + incoming_message);
}
socket.close();
}
catch(IOException iex){
iex.printStackTrace();
}
}
}
If you will take a look at source code of PrintWriter constructor you used, you will spot that it invoke another constructor with autoFlush = false.
I suppose, you should change it to:
PrintWriter printer = new PrintWriter(socket.getOutputStream(), true);

Java Server/Client string delay

i am creating a LAN game that accepts strings and parses them from structured english and displays them on a grid. i have created the server and client and it works but im having some issues. when i send a string it doesnt appear on the other machine right away. for some reason the string is only sent to the other machine once the other machine sends something over. i dont know why this happens. Could you please help me find out why it doesnt send straight away. Thanks
Server Code:
import java.awt.Point;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class studentServer{
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();
public ServerPlayergameMain gm;
public static void main(String args[]) throws Exception{
}
public void run(String commandMessage){
while(true){
try{
printWriter.println(commandMessage+"\n");
String input = bufferedReader.readLine();//reads the input from textfield
console.readLine("Client message: "+input);//Append to TextArea
}catch(Exception e){}
}
}
public void serverStartActionPerformed() {
System.out.println("Server has started!");
try{
serverSocket = new ServerSocket (8888); // socket for the server
socket = serverSocket.accept(); // waiting for socket to accept client
JOptionPane.showMessageDialog(null, "Your opponent has connected!", "Opponent Connection!", JOptionPane.INFORMATION_MESSAGE);
gm = new ServerPlayergameMain();
gm.setVisible(true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads line from input streamer
printWriter = new PrintWriter(socket.getOutputStream(),true);
}catch(IOException | HeadlessException e){
System.out.println("Server not running!"); //print message if server is not running
}
}
}
Client Code:
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();
public ClientPlayergameMain gm;
public void Clients(String address) {
try{
socket=new Socket("localhost",8888);//Socket for client
//below line reads input from InputStreamReader
bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//below line writes output to OutPutStream
printWriter=new PrintWriter(socket.getOutputStream(),true);
JOptionPane.showMessageDialog(null, "Connected to server successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
gm = new ClientPlayergameMain();
gm.setVisible(true);
System.out.println("Connected");//debug code
}catch(Exception e){
JOptionPane.showMessageDialog(null, "No Connection to server", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println("Not Connected");
}
}
public static void run(String commandMessage){
while(true){
try{
printWriter.println(commandMessage+"\n");
String input = bufferedReader.readLine();
System.out.println("From server:" +input);
}catch(Exception e) {}
}
}
}
The code works but i dont know why there is a condition for the other machine to send something.
Thanks for your time.
A lot of compilation problems are there in you code. Some of the classes and objects are missing to resolve.
Still I have tried it to figure out the issue.
It may be the reasons:
sending new line character \n in printWriter.println(commandMessage+"\n"); statement, just remove \n.
client and server both are writing first in printWriter.println(commandMessage+"\n"); statement, make it last in anyone class
Here is the code:
StudentServer.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class StudentServer {
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
public static void main(String args[]) throws Exception {
StudentServer studentServer = new StudentServer();
studentServer.serverStartActionPerformed();
studentServer.run("server");
}
public void run(String commandMessage) {
if (true) {
try {
printWriter.println(commandMessage);
String input = bufferedReader.readLine();// reads the input from textfield
System.out.println("Client message: " + input);// Append to TextArea
} catch (Exception e) {
}
}
}
public void serverStartActionPerformed() {
System.out.println("Server has started!");
try {
serverSocket = new ServerSocket(8888); // socket for the server
socket = serverSocket.accept(); // waiting for socket to accept client
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads
// line
// from
// input
// streamer
printWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Server not running!"); // print message if server is not running
}
}
}
StudentClient.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
public void clients() {
try {
socket = new Socket("localhost", 8888);// Socket for client
// below line reads input from InputStreamReader
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// below line writes output to OutPutStream
printWriter = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Connected");// debug code
} catch (Exception e) {
System.out.println("Not Connected");
}
}
public void run(String commandMessage) {
if (true) {
try {
String input = bufferedReader.readLine();
System.out.println("From server:" + input);
printWriter.println(commandMessage);
} catch (Exception e) {
}
}
}
public static void main(String args[]) throws Exception {
StudentClient studentClient = new StudentClient();
studentClient.clients();
studentClient.run("client");
}
}
Have you tried printWriter.flush() after each write/print?
There are quite a few little problems, as Braj points out. The main one is in this sequence on your server side:
serverSocket = new ServerSocket (8888); // socket for the server
socket = serverSocket.accept(); // BLOCKS waiting for socket to accept client
// ..
printWriter = new PrintWriter(socket.getOutputStream(),true);
This means that printWriter, which you use to write to the client, doesn't even exist until after the server has listened for, blocked waiting on, and accepted a connection from the client.
If you want the connection to be opened for reading and writing without seeming to send anything from the client, send a handshake from the client. You could copy SMTP, and use HELO <myname>. That even tells the server who's calling.
Update after further reading:
I've always done like you have, and used the implicit connect that happens when you use getOutputStream() on the client side. However, Socket does allow you to connect an existing socket manually, using Socket#connect(). Try that, maybe it will work better than a handshake, for you.

Keeping a java server open after the client sends a message

I am having an issue figuring out how to keep a connection open with my server class. When it connects I want the client to send to the server that a client has connected, which it does. My issue is that right after it receives the message the java file stops running. Could anybody give me some advice on how to keep the Server waiting for a message from the user until a certain message is received? Thank you in advance, will be researching in the mean time.
Client class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
PrintStream ps1 = new PrintStream(clientSocket.getOutputStream());
ps1.println("A client has successfully connected.");
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
System.out.println(message);
}
}
Server class:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
}
use the while loop for continuouly running your server and compare the received message with the desired end message ( bye ) with the if condition, the code is given below,
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
while(true)
{
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
if(message.equals("bye"))
break; // breaking the while loop.
} // end of while loop.
}

remote java console application control using cmd

I have Java console app, which i want to control from another computer. I use Socket class to send data through net and pipeline to connect the remote controlled program with Sender and Reader program, as shown:
Reader:
import java.io.*;
import java.net.*;
public class Reader {
//reads information from the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
PrintWriter bw = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
bw.println(vstup);
} while(true);
s.close();
}
}
Sender:
import java.io.*;
import java.net.*;
public class Sender {
//sends instruction to the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
System.out.println(vstup);
} while(true);
s.close();
}
}
RemoteController:
import java.net.*;
import java.io.*;
public class RemoteController {
public static void main(String[] main) throws IOException {
ServerSocket ss = new ServerSocket(Integer.parseInt(main[0]));
System.out.println("Done, please connect the program.");
Socket reader = ss.accept(); //reads what the program says
System.out.println("reader connected");
Socket writer = ss.accept(); //writes into the program
System.out.println("writer connected");
BufferedReader read = new BufferedReader(new InputStreamReader(reader.getInputStream()));
PrintWriter write = new PrintWriter(writer.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i<5; i++) {
write.println(br.readLine());
System.out.println(read.readLine());
}
write.close();
read.close();
writer.close();
reader.close();
ss.close();
}
}
now i run the Remote controller and then i write
java Sender localhost 1234 | java SomeProgram | java Reader localhost 1234
into a comand prompt to test whenever it works. It sometimes works, sometimes not, any advise how to make it work everytime?
All the problem was that the Sender and Reader programms conected in a random order to the main program, so adding Thread.sleep(200) resolved my problem, sorry for annoying.
PS: If you program in java (and cmd), try it, iƄ really fun i think.

java tcp client and server

I have the following host
package clserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Main {
//instance vars
static ServerSocket sSocket = null;
static int serverPort = 0;
static Socket cSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void main(String[] args) throws IOException {
System.out.println("\n\n\nTCP Server Client\n\nEnter port number:");
Scanner scan = new Scanner(System.in);
serverPort = scan.nextInt();
try {
//connect server to port
sSocket = new ServerSocket(serverPort);
} catch (IOException ex) {
System.err.println("That port is busy");
}
try {
//accept client connection
cSocket = sSocket.accept();
} catch (IOException ex) {
System.err.println("Connection failed");
}
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
System.out.println(in.readLine());
}
}
and this client code
package clclient;
import java.io.*;
import java.net.*;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
//instance vars
static Socket cSocket =null;
static PrintWriter out = null;
static BufferedReader in = null;
//server info
static String serverName = null;
static int serverPort = 0;
public static void main(String[] args) {
try {
System.out.println("\n\n\nTCP Chat Client\nEnter server name:");
Scanner scan = new Scanner(System.in);
//get server info from user
serverName = scan.nextLine();
System.out.println("\nEnter port number:");
serverPort = scan.nextInt();
//make connection to server
cSocket = new Socket(serverName, serverPort);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
} catch (UnknownHostException ex) {
System.err.println("\ncan't find that host\n");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String nm = "testing";
out.print(nm);
}
}
I am trying to send messages back and forth between them but when I send a message the host crashes. It throws the exception Java.net.SocketException:connection reset
Nope. print() just sends the data. println() sends the data and a line terminator. readLine() blocks until a line terminator is received. So somewhere along the line you have to call println(), or send a line terminator some other way.
I haven't used Java sockets for a while, but the following fixes it on my machine:
In the client, call out.println(nm) instead of out.print(nm).
I think it may have something to do with automatic flushing, where println autoflushes but print does not. Still, not sure off the top of my head why print would cause a Socket exception.
Edit: you really should be doing everything with the Sockets within a try, and have a finally that calls close() on the Sockets.

Categories