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.
Related
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();
}
}
}
I am new to networking and I am trying to write the server client program. Still, I keep getting Address already in use and cant chat. A friend of mine run this in his pc and it was working. Can somebody explain to me why I keep getting this error?
Here is the server class:
import java.net.*;
import java.io.*;
class server
{
public static void main(String []args)
{
try
{
ServerSocket serv = new ServerSocket(8001);
System.out.println("Server up and listening:");
Socket S = serv.accept();
InetAddress obj = S.getInetAddress();
System.out.println("Request coming from:");
BufferedReader br = new BufferedReader(new InputStreamReader(S.getInputStream()));
String msg = br.readLine();
System.out.println("Message recieved:"+msg);
br.close();
serv.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}}
Here is the client class:
import java.net.*;
import java.io.*;
import java.util.*;
class client`{
public static void main(String [] args)
{
Socket s = null;
BufferedOutputStream bout = null;
InetAddress obj = null;
try {
obj = InetAddress.getByName(args[0]);
s = new Socket(obj, 8001);
String str = new Scanner(System.in).nextLine();
byte[] arr = str.getBytes();
bout = new BufferedOutputStream(s.getOutputStream());
bout.write(arr);
bout.flush();
bout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} }
I appreciate any help you can provide!
use below command to determine if you have any open port on the machine where you are running your Server program
netstat -nao | find "8001"
You can simply change 8001 to another value. It looks like that it is under use by another program. Depends on your operating system, there are plenty ways to learn which ports are occupied.
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.
I am working on client-server chat program.
I have the two programs as follows:
client.java
import java.io.*;
import java.net.*;
import java.util.*;
class client {
public static void main(String[] args) throws IOException{
// ServerSocket SerSock = new ServerSocket(8090);
Socket cliSock = new Socket("localhost",8090);
BufferedReader in = new BufferedReader(new InputStreamReader(
cliSock.getInputStream()));
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(
cliSock.getOutputStream()));
// out.write("some data".getBytes());
Scanner scan = new Scanner(System.in);
String message="";
message = in.readLine();
System.out.println(message);
// while((message = in.readLine()) != "bye")
// {
// System.out.println(message);
// System.out.println("I am in while in client");
// out.write(scan.nextLine());
// }
in.close();
out.close();
cliSock.close();
// SerSock.close();
}
}
server.java
import java.io.*;
import java.net.*;
import java.util.*;
class server {
public static void main(String[] args) throws IOException{
ServerSocket SerSock = new ServerSocket(8090);
System.out.println("Waiting for client...");
Socket cliSock = SerSock.accept();
// open();
// while ( !cliSock.isConnected())
// {
// }
BufferedReader in = new BufferedReader(new InputStreamReader(
cliSock.getInputStream()));
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(
cliSock.getOutputStream()));
Scanner scan = new Scanner(System.in);
String message = "Hello client";
System.out.println(message);
out.write(message);
// while((message = in.readLine()) != "bye")
// {
// System.out.println("I am in while in server");
// System.out.println(message);
// message = scan.nextLine();
// out.write(message);
// }
in.close();
out.close();
cliSock.close();
SerSock.close();
}
}
Basically, I wanted to make a chat server program so that both can chat until they get bye message. I am unable to implement the program. The error is as follows:
Exception in thread "main" java.net.SocketException: Socket closed
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:121)
at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:316)
at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
at java.io.BufferedWriter.close(BufferedWriter.java:266)
at server.main(server.java:44)
I am novice in java. Please help me in solving the problem.
If you want to chat back and forth, stop closing your Input and Output Streams. Also, closing either stream on a Socket is equivalent to closing the Socket itself.
You should create a loop to keep reading new data from your Sockets
BufferedReader br = new BufferedReader(so.getInputStream());
while(true) {
String line = br.readLine();
...
}
If you are uncertain how to correctly use a class, or if an instance is behaving in a way you do not understand, then your first recourse should be to read the class's documentation.
If you had done so in this case, then you would have found that closing either the input stream or the output stream of a Socket closes the whole Socket. Your exception is being thrown when class server attempts to close a Sockets output stream after already closing its input stream. Note also that Socket.close() will close both streams, so you could just use that (only).
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.