Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to do a socket connection for client and server to display the list of files. but below code is not taking any input from server or giving output to client. Please help.
Server
package javaapplicationthread;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
public class zs {
public static int reads,red;
public static void main(String[] args)
{
int flg=0;
try{while(true){
ServerSocket serverSocket = new ServerSocket(1312);
Socket clientSocket = serverSocket.accept();
BufferedReader bufferedReader;
PrintWriter outk=new PrintWriter(clientSocket.getOutputStream(),true);
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = bufferedReader.readLine();
System.out.println("input is"+ inputLine);
outk.write("abc");
File inputFolder = new File(inputLine);
System.out.println("control is being sent to traverse");
traverse(inputFolder, "");
}
}
catch (IOException ex) {
System.out.println("my exception is"+ex)
System.out.println(leftIndent + parentNode.getName());
}
}}
In the client, when you do redd = b.readLine(); you are asking to read an entire line. But in the server you haven't sent an entire line: you've only asked it to write three characters:
outk.write("abc");
None of those three characters is actually sent, however, because the PrintWriter buffers them temporarily. To fix it, change that line to:
outk.println("abc");
Or:
outk.write("abc\n");
outk.flush();
After that change, the client successfully displays: result is abc.
it is not giving any errors
They're both giving errors... The client throws an exception when the readLine call fails. The server throws an exception when it begins the next iteration of the while(true) loop and tries to recreate the socket it is still using. You probably want to move the creation of the ServerSocket outside the while loop.
Related
This is a simple chat program in Java. I know I can get the work done by 1 socket but I was wondering why not use 2 sockets?
This executes but does not work as intended. Kindly see the code and find the error. Please help me as i am new to this.
Server code is below.
Server.java
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args)throws IOException {
ServerSocket ss=new ServerSocket(10001);
Socket s=ss.accept();
Socket s1=new Socket("localhost",10005);
DataInputStream di=new DataInputStream(s.getInputStream());
DataOutputStream dot=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1="",str="";
while(str1!="exit"){
str=(String)di.readUTF();
System.out.println("message="+str);
System.out.println("Enter message:");
str1=br.readLine();
dot.writeUTF(str1);
dot.flush();
}
di.close();
dot.close();
s1.close();
s.close();
ss.close();
}
}
Client code is below kindly tell the problem.
i know i can get the work done by 1 socket but i was trying why not use 2 sockets.
Client.java
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) throws IOException{
ServerSocket ss;
ss = new ServerSocket(10005);
Socket s=ss.accept();
Socket s1=new Socket("localhost",10001);
DataInputStream di=new DataInputStream(s.getInputStream());
DataOutputStream dot=new DataOutputStream(s1.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str1="";
while(str1!="exit"){
System.out.println("Enter message:");
str1=br.readLine();
dot.writeUTF(str1);
dot.flush();
str=(String)di.readUTF();
System.out.println("message="+str);
}
dot.close();
di.close();
s1.close();
ss.close();
}
}
Yes, you can open (within reason) as many sockets as you want from a single JVM.
The problem with your code that you're using a blocking API, meaning that the thread doesn't return from the call br.readLine() and so it cannot do any more work (including waiting for data on other sockets).
You've got a couple of options:
create a thread per socket (being careful of resource limitations).
use the NIO API that is inherently non-blocking.
There are two problems you will need to fix to make your program work:
Both server and client passively open a socket first and then both wait for the other one to connect first (ss.accept()). Solution: In client.java, move the the line ss.accept() below the active open Socket s1=new Socket("localhost",10001);.
The server uses socket s for input and output. You probably want to use s1 as output. Solution: In server.java, in the line DataOutputStream dot=new DataOutputStream(s.getOutputStream());: replace s with s1.
Please let me know if the program now works as expected.
For your future experiments, you might want to have a look at this tutorial on NIO selectors or threaded network application models, as Nick Holt suggested.
I try to make a little Server-Client connection.
They both have a Scanner and a PrintWriter, and they are writing to each other using a Socket's input and output stream.
Client.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static Scanner scanner;
public static void main(String[] args) throws UnknownHostException, IOException {
socket = new Socket("localhost", 13344);
scanner = new Scanner(socket.getInputStream());
printWriter = new PrintWriter(socket.getOutputStream());
printWriter.println("dataline 1");
printWriter.println("dataline 2");
printWriter.println("dataline 3");
printWriter.flush();
//Error!? => I never got the echo from server in output
while (scanner.hasNextLine()) {
String lineRead = scanner.nextLine();
System.out.println("From server" + lineRead);
}
socket.close();
scanner.close();
printWriter.close();
System.out.println("Client has quit.");
}
}
Server.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static Scanner scanner;
public static void main(String[] args) throws IOException {
serverSocket = new ServerSocket(13344);
System.out.println("Waiting for Client to connect");
socket = serverSocket.accept();
scanner = new Scanner(socket.getInputStream());
printWriter = new PrintWriter(socket.getOutputStream());
System.out.println("Client has connected!!");
while (scanner.hasNextLine()) {
String lineRead = scanner.nextLine();
System.out.println("From Client: " + lineRead);
}
//Error!? => This line never runs
System.out.println("Now sending echo to Client");
printWriter.println("Echo from server1");
printWriter.println("Echo from server2");
printWriter.flush();
socket.close();
printWriter.close();
scanner.close();
System.out.println("Server has quit.");
}
}
I start the server: java Server.java
I start the client: java Client.java
Server's output:
Waiting for client to connect
Client has connected!!
From Client: dataline 1
From Client: dataline 3
From Client: dataline 3
Client's output is empty, not a word on it.
As you can see Server's code termination stops AFTER it is read from Client's output stream, and Client's code termination stops BEFORE it could read from Server's output stream.
My question is:
How this Scanner-PrintWrier communication works, how do i know if a printWriter printed BEFORE a scanner could read in a server-client connection like this? What i did wrong and why? How to use properly a scanner?
E D I T:
#T.C Do you mean like this? Now i got full output, both Server and Client are quit after they are sent and received data.
I modified like this:
String line = "";
while (!line.equals("#")) {
line = scanner.nextLine();
if (!line.equals("#")) {
System.out.println("From server" + line);
}
}
The Scanner.hasNext*() methods will block to wait for input to scan, so you can't use it to detect when the client has finished sending.
Simplest way to solve this problem would be to have the client send a special string telling the server it's done sending.
I have already posted some samples on client-server communication with detailed description.
Please have a look at below post that might help you to understand it better.
Multiple clients access the server concurrently
Java Server with Multiclient communication.
Try with BufferedReader that contains ready() that tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
You can try with InputStream#available() but it doesn't have read line method.
Go with the solution suggested by #T.C. but he is not provided any sample code on it. You can find in it my post.
Had almost the exact same problem, after banging my head in the keyboard for a couple of hours, this is what saved me:
printWriter = new PrintWriter(socket.getOutputStream(), true);
The second parameter sets auto-flushing to true.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write a program that just reads and write an unbuffered steam, and reads and writes a buffered stream. Following the example on the java docs, I've got this for my buffered stream, which works fine.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("unbufferedread.txt");
outputStream = new FileWriter("unbufferedwrite.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
// Add finally block incase of errors.
// Display error if input file is not found.
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
However the Java docs say "Here's how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O:".
inputStream = new BufferedReader(new FileReader("bufferedread.txt"));
outputStream = new BufferedWriter(new FileWriter("bufferedwrite.txt"));
My question is how to implement it. Is it possible to add it all to one class? When I try to add it, I get an error saying:
"Cannot find symbol - class BufferedReader"
Any help would be great. Thanks.
You have to import the java.io.BufferedReader and java.io.BufferedWriter classes. Based on the code you posted, you aren't doing that. So just add the two lines:
import java.io.BufferedReader;
import java.io.BufferedWriter;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
To execute process/command in bash from java one can use the following class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CmdExecutor {
public CmdExecutor(){
}
public void exe(String [] args) throws IOException{
if (args.length <= 0) {
System.out.println("empty command");
return;
}
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
However. What if the process don't terminate(yet). It does calculations and output it in the shell. I want to be able to run the process in another thread and get changes in the output, like frame by frame strings. How can this be achieved?
Check out
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html
You may want to have one thread (producer) reading process output, and putting them into a LinkedBlockingQueue (queue.put), then have another thread (consumer) to get elements from the queue (queue.poll) and process it.
package montecarlo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author hafiz
*/
public class PICalcDistributedMaster {
ObjectOutputStream ostream;
ObjectInputStream istream;
Socket s;
String numThrows;
public void go(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter number of throws: ");
numThrows = input.next();
int num = Integer.parseInt(numThrows);
try{
ServerSocket sock = new ServerSocket(100);
s = new Socket("127.0.0.1",100);
System.out.println("Waiting for connection");
System.out.println("Connection received from " + s.getInetAddress());
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("Sending Number");
pw.println(num);
ostream = new ObjectOutputStream(s.getOutputStream());
ostream.flush();
istream = new ObjectInputStream(s.getInputStream());
System.out.println("IO streams found");
istream.read(); //reads the input stream
}
catch (IOException ie){
ie.printStackTrace();
}
}
public static void main(String [] args){
PICalcDistributedMaster pim = new PICalcDistributedMaster();
pim.go();
}
}
i have adjusted the code to what you told me.I am still getting an error after running it more than once and i think it has to do with the garbage collector problem.My error is
java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:365)
at java.net.ServerSocket.bind(ServerSocket.java:319)
at java.net.ServerSocket.<init>(ServerSocket.java:185)
at java.net.ServerSocket.<init>(ServerSocket.java:97)
at montecarlo.PICalcDistributedMaster.go(PICalcDistributedMaster.java:31)
at montecarlo.PICalcDistributedMaster.main(PICalcDistributedMaster.java:56)
I assume the problem is with the socket it is binding to.I have tried different kinds but i cant still proceed
I'd like to suggest programming in smaller chunks. You've got a lot of code here and I don't think most of it ever runs:
ServerSocket sock = new ServerSocket(5000);
s = new Socket("127.0.0.1",5000);
s = sock.accept();
This code creates a server socket, binds it to a port.
Then you create a new socket s to connect to the server socket. (Which isn't yet listening.)
You destroy your new socket s with the sock.accept() result -- when you lose the last reference, the socket is free for garbage collection, and you only ever had one reference to it -- s.
The sock.accept() call probably ought to block until a new connection arrives. If it doesn't block, that means you triggered an exception even before all this code.
Incidentally, there's another instance of overwriting content nearly immediately after creating it:
String message = "connection successful";
message = (String) istream.readObject();
You'll never see connection successful from your program because you've overwritten the only reference you have to the string.
Probably the most egregious error in the entire program -- the one that is keeping you from making any real forward progress -- is that you throw away all the exception information:
try{
go(null);
}
catch(Exception e){
System.err.print("Connection terminated");
}
The catch(Exception e) { /* print message */ } means that you don't get any diagnostic information about what errors actually happened in your program. (Since you never use the parameter of go(), you should remove it completely and the needless null here, as well.)
One of these catch-all catch statements might be useful once you're confident that your product catches everything more specific, is nearly bullet-proof, and your customers demand an always-on reliable product. But it has no place in development -- you need to be alerted to faults in your programs with as much detail as possible so you can find and fix all your bugs.
Remove this. Get rid of your process() method completely -- it is only harmful.