Hi I'm facing a little problem with eof()
I created a tcp connection between a client and a server to send text to the server and
receive it back in capital letters but the problem is that it's reading one line only so
I would like to modify the code so it reads until I type "stopp". When I type stop both
the client and the receiver terminate at the same time.
This is the client class
import java.io.*;
import java.net.*;
public class Klient {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException,
IOException {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
while (true){
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
}
//clientSocket.close();
}
}
This is the server class
import java.io.*;
import java.net.*;
public class TCPServer {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
It is only reading one sentence because the server does not repeatedly ask for new input. Sure, you have a while(true) loop, but that loop is repeatedly accepting new connections (this is what welcomeSocket.accept() does). Once you asked for one line input, you go back to the start of the loop, and waits for another connection to come. Of course, no more connections are coming, so the server just does nothing forever.
You should add an inner loop,
while (true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equalsIgnoreCase("stop")) {
connectionSocket.close();
break;
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
Once the server receives "stop", it would close the connection with the current client, and wait for another client to connect as it goes back to the top of the outer loop. If you want the server to terminate completely (so only accepting one connection), just remove the outer loop, and close the welcomeSocket:
ServerSocket welcomeSocket = new ServerSocket(6789);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equalsIgnoreCase("stop")) {
connectionSocket.close();
break;
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
welcomeSocket.close();
As for the client, it can break out of the loop when inFromServer.readLine returns null, which is indication that the connection has been closed.
while (true){
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
if (modifiedSentence == null) {
break;
}
System.out.println(modifiedSentence);
}
Related
Hello i have a client server program and the server side works while the client side is having some problems. The client prints out a message once it connects, but after some user input (which is not used yet) i get this error. The server prints out a text file with line numbers and sequence numbers(seq nums aren't quite right yet) and is supposed to send the line numbers, seq numbers and lines of text to the client.
Server:
public class STSServer {
/**
* #param args the command line arguments
*/
public static void main(String argv[]) throws Exception
{
String startLineFromClient;
String endLineFromClient;
String stringLineNumber;
String stringSeqNumber;
String test = "hello";
int convertStart;
int convertEnd;
int subtractStartEnd;
int temp;
int byteTransfer;
int lineNumber = 0;
int sequenceNumber;
ServerSocket welcomeSocket = new ServerSocket(6789);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
try{
File myFile = new File("alice.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
startLineFromClient = inFromClient.readLine();
endLineFromClient = inFromClient.readLine();
convertStart = Integer.parseInt(startLineFromClient);
convertEnd = Integer.parseInt(endLineFromClient);
while((line = bufferedReader.readLine()) != null)
{
sequenceNumber = line.length();
System.out.print(lineNumber);
stringLineNumber = Integer.toString(lineNumber);
outToClient.writeBytes(stringLineNumber);
System.out.print(" ");
System.out.print(sequenceNumber);
stringSeqNumber = Integer.toString(sequenceNumber);
outToClient.writeBytes(stringSeqNumber);
System.out.print(" ");
System.out.print(line);
outToClient.writeBytes(line);
System.out.println("");
lineNumber++;
//stringLineNumber = Integer.toString(lineNumber);
//stringSeqNumber = Integer.toString(sequenceNumber);*/
// outToClient.writeBytes(test);
}
fileReader.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Client:
public class STSClient {
public static void main(String argv[])throws Exception
{
String startLine;
String endLine;
String lineNumber;
String seqNumber;
String line;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (true)
{
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++ Simple TCP Service (STS)+++++");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("Command allowed by the server for this client:");
System.out.println("download [starting line #] [ending line #]");
System.out.print("Command: ");
startLine = inFromUser.readLine();
endLine = inFromUser.readLine();
outToServer.writeBytes(startLine + '\n');
outToServer.writeBytes(endLine + '\n');
lineNumber = inFromServer.readLine();
seqNumber = inFromServer.readLine();
line = inFromServer.readLine();
System.out.print(lineNumber);
System.out.print(seqNumber);
System.out.print(line);
System.out.println("");
}
}
}
Error:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at stsclient.STSClient.main(STSClient.java:42)
Your client is reading lines.
Your server is not sending lines.
Your server exits without closing the socket, which resets it on Windows.
Your client is still stuck in the first readLine() waiting for a line terminator.
It gets a connection reset instead.
Solution: send lines, and don't exit without closing the socket.
I'm trying to implement basic TCP communication via sockets and the problem is that it doesn't work. When I enter few sentences from client, the server receives only the first sentence and reply it back.
Client :
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5055);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(!(sentence = inFromUser.readLine()).equals("end")) {
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
clientSocket.close();
Server:
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(5055);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
I have this code but it doesn't run on cmd using windows. Doing this for the first time. When I try to run the server, there is no response (no error, but can't continue typing and nothing happens, and the same for the client1.
This is the code for the server:
import java.io.*;
import java.net.*;
public class outputStream
{
public static void main (String args [])throws Exception {
// initialises Server Socket
ServerSocket welcomeSocket = new ServerSocket (1337);
// waits for the connection of two clients C1 and C2 (in either order)
while (true) {
Socket socket1 = welcomeSocket.accept();
Socket socket2 = welcomeSocket.accept();
//gets input streams of the clients
BufferedReader inFromclient1 = new BufferedReader (new InputStreamReader(socket1.getInputStream()));
BufferedReader inFromclient2 = new BufferedReader (new InputStreamReader(socket2.getInputStream()));
//reads the data
String client1Sentence = inFromclient1.readLine();
String client2Sentence = inFromclient2.readLine();
//get output streams of the clients
BufferedWriter outToclient1 = new BufferedWriter (new OutputStreamWriter (socket1.getOutputStream ()));
BufferedWriter outToclient2 = new BufferedWriter (new OutputStreamWriter (socket2.getOutputStream ()));
//replies to clients
String reply1 = " ";
String reply2 = " ";
if (client1Sentence.equals(client2Sentence)){
reply1 = "xxxxx\n";
reply2 = "yyyyy\n";
} else if (client1Sentence.equals ('y') && client2Sentence.equals ('z')) {
reply1 = "xxx\n";
reply2 = "yyyyyy";
}
else if (client1Sentence.equals ('z') && client2Sentence.equals ('y')) {
reply1 = "xxxx\n";
reply2 = "yyyy\n";
}
else if (client1Sentence.equals ('y') && client2Sentence.equals ('x')) {
reply1 = "xxxxxxxx\n";
reply2 = "yyyyy\n";
}
else if (client1Sentence.equals ('P') && client2Sentence.equals ('R')) {
reply1 = "xxxxxxx\n";
reply2 = "yyyy\n";
}
else if (client1Sentence.equals ('z') && client2Sentence.equals ('x')) {
reply1 = "xxxx\n";
reply2 = "yyyyyyy\n";
}
else if (client1Sentence.equals ('x') && client2Sentence.equals ('z')) {
reply1 = "xxxxx\n";
reply2 = "yyyyyyy\n";
}
//sends reply to clients
outToclient1.write(reply1,0,reply1.length());
outToclient2.write(reply2,0, reply2.length());
//ends connection
outToclient1.flush();
outToclient2.flush();
}
}
}
This is the code for Client1:
import java.io.*;
import java.net.*;
public class client1
{
/**
* Constructor for objects of class clientTCP
*/
public static void main (String args[]) throws Exception {
//intialises input/outputStream
BufferedReader inFromUser = new
BufferedReader (new InputStreamReader (System.in));
//intialises client Socket
Socket clientSocket = new Socket ("localhost",1337);
//fetches input/outputSteam
BufferedReader inFromServer = new BufferedReader (new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter outToServer = new BufferedWriter (new OutputStreamWriter(clientSocket.getOutputStream ()));
//sends message to server and closes server connection
String sentence = inFromUser.readLine();
outToServer.write (sentence + "\n", 0, sentence.length()+1);
outToServer.flush();
//server reads line from client
String ack = inFromServer.readLine();
//server replies to client
System.out.println ("FROM SERVER:" + ack);
// client socket is closed
clientSocket.close();
}
}
welcomeSocket.accept() will block until a client connects, so unless you run two clients and one server, nothing will happen
The problem goes with the use of the equals(), the arguments should be enclosed in a double quotation and not a single quotation.
Client will request for a file, if the file exist in server then the server send the file and give a confirmation message. So i want to take input using the main while loop but it stops working after first iteration,
client side
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class WebClient {
public static void main(String[] args) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
String req;
System.out.println("Do you want to search? (Y/N): ");
Scanner user_input = new Scanner(System.in);
req = user_input.next();
while (req.equals("Y")) {
Socket clientSocket = new Socket("localhost", 2000);
System.out.println("Enter the file name: ");
String file = inFromUser.readLine();
DataOutputStream serverOutput = new DataOutputStream(clientSocket.getOutputStream());
serverOutput.writeBytes(file + '\n');
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Text from the file: ");
while (true) {
String data = serverInput.readLine();
if (data == null) {
break;
}
System.out.println(data);
}
clientSocket.close();
System.out.println("Do you want to search again? (Y/N): ");
req = user_input.next();
}
}
}
server side
import java.io.*;
import java.net.*;
public class WebServer {
public static void main(String[] args) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(2000);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String file = inFromClient.readLine();
System.out.println("Client Request: " + file); //Show The Client Request File
String path = ("E://From Varsity//4.2//Lab//Network Programming//Java trying//New TCP-Client+Server//tcp")+ "/" + file ;
File objfile = new File(path);
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
if (objfile.exists())
{
String readfile = rfile(path);
outToClient.writeBytes("\n" +readfile + "200 ok \n"); // when exact file find
}
else
{
outToClient.writeBytes("404 The Requested File not found \n"); // file not found
}
}
}
public static String rfile(String file_N) throws Exception
{
StringBuilder app = new StringBuilder();
BufferedReader bufferR = new BufferedReader(new FileReader(file_N));
try
{
String line = bufferR.readLine(); // read file from buffer
while (line != null) {
app.append(line); // append the line
app.append("\n");
line = bufferR.readLine();
}
}
finally
{
bufferR.close();
}
return app.toString();
}
}
Any help will be appreciated , thanks in advance
java.net.Socket is blocking. It'll block until it receives a close (the call to readLine() blocks until more data is available)
3 solutions:
Simplest: add outToClient.close() after the write.
Nonblocking: Use java.nio.SocketChannel/java.nio.ServerSocketChannel
Threaded: Create a new thread each time ServerSocket.accept() fires with the Socket object from accept.
How can I send the file listing to client from server using Socket programming. I have used DataOutputStream and PrintWriter, both returns only one file name to Client. I know there is some problem in '\n'. But unable to solve it. Awaiting experts advice ... Thank you.
Client
switch (choice) {
.......
case 2: // for viewing files in the client's directory
Socket mysocket = new Socket("localhost", 6103);
String user_name = username;
DataOutputStream outToServer2= new DataOutputStream(mysocket.getOutputStream());
outToServer2.writeBytes(user_name + '\n');
BufferedReader inFromServer2 = new BufferedReader(newInputStreamReader(mysocket.getInputStream()));
String list = inFromServer2.readLine();
System.out.println("FROM SERVER - LIST OF FILES:" + list);
break;
}
.......
Server
import java.io.*;
import java.net.*;
class DirList
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6103);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
clientSentence = inFromClient.readLine();
System.out.println("Received view files request from user: " + clientSentence);
String path = "/home/user/Files/";
String userdir = path + clientSentence;
String text="";
String capitalizedSentence1;
File f = new File(userdir);
File[] listOfFiles = f.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
text = listOfFiles[j].getName();
outToClient.println(text);
System.out.print(text+' ');
}
}
}
}
}
You need to flush the output from your server:
outToClient.flush();
Also, in your client, you need to place the read in a loop to consume all the output:
String line = null;
while ((line = inFromServer2.readLine()) != null) {
System.out.println(line);
}
Try using "\r\n". It might solve your problem.