Can't run TCP client/server code on using cmd - java

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.

Related

My server program is unable to send data to the client program I wrote

So the the server program consists of the following code:
import java.io. * ;
import java.net. * ;
import java.util. * ;
public class TimeServer {
public static void main(String[] args) {
try {
//Create sockets
ServerSocket ss = new ServerSocket(60000);
Socket rs = ss.accept();
//create streams
BufferedInputStream bs = new BufferedInputStream(rs.getInputStream());
InputStreamReader isr = new InputStreamReader(bs);
BufferedOutputStream bos = new BufferedOutputStream(rs.getOutputStream());
PrintWriter pw = new PrintWriter(bos);
//set timeout
rs.setSoTimeout(20000);
int c = 0;
StringBuilder sb = new StringBuilder();
//while loop reads in a character until a period (includes period)
while (((char) c != '.')) {
c = isr.read();
//append each char to a string builder
sb.append((char) c);
}
//convert stringbuilder to string
String str = sb.substring(0);
//If string equals "time." returns time else error message
if (str.compareTo("time.") == 0) {
Date now = new Date();
pw.print("time is: " + now.toString());
pw.flush();
}
else {
pw.print("Invalid syntax: connection closed");
pw.flush();
}
//close socket
rs.close();
//close serversocket
ss.close();
} catch(IOException i) {
System.out.println(i.getMessage());
}
}
}
The code for the client is:
import java.io. * ;
import java.net. * ;
import java.util. * ;
public class TimeClient {
public static void main(String[] args) {
try {
//create socket
Socket sock = new Socket("localhost", 60000);
//create streams
BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
InputStreamReader isr = new InputStreamReader(bis);
BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream());
PrintWriter pw = new PrintWriter(bos);
//set timeout
sock.setSoTimeout(20000);
//write argument to stream, argument should be "time." to recieve time
pw.write(args[0]);
pw.flush();
int c = 0;
StringBuilder sb = new StringBuilder();
//while loop reads each character into stringbuilder
while ((c != -1)) {
c = isr.read();
sb.append((char) c);
}
//stringbuilder converted to string and printed
String str = sb.substring(0);
System.out.println(str);
//socket closed
sock.close();
} catch(IOException i) {
System.out.println(i.getMessage());
}
}
}
The problem is that if I run each program in a separate cmd.exe, they do not communicate despite using localhost as the IP address. I can't seem to find the logical error in the code which causes this and wondered if anyone could help?
The problem is that you are using a BufferedOutputStream and you close the socket immediately after writing on the PrintWriter. What you have written remains in the buffer and the socket is closed before anything has been sent to the client.
You need to flush before closing in order to force the content of the buffer to be sent:
...
//close socket
pw.flush();
rs.close();
...
TimeClient contains a minor error: you loop receiving until you get a -1 which is correct, but you append that -1 to the StringBuilder which is wrong. It should be:
//while loop reads each character into stringbuilder
while(true){
c = isr.read();
if (c == -1) { break; }
sb.append((char) c);
}
But this should never prevent the text to be displayed...

While Loop not working as it should be

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.

Java Socket - send many message

I have two simple classes:
Client:
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName(null);
Socket socket = null;
try {
socket = new Socket(addr, 1050);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, false);
stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// read user input
while (true) {
userInput = stdIn.readLine();
System.out.println("Send: " + userInput);
out.println(userInput);
out.flush();
String line = in.readLine();
while(line != null){
System.out.println(line);
line = in.readLine();
}
System.out.println("END");
}
}
catch (UnknownHostException e) {
// ...
} catch (IOException e) {
// ...
}
// close
out.close();
stdIn.close();
socket.close();
}
Server:
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter out = new PrintWriter(bw, /*autoflush*/true);
private void sendMessage(String msg1, String msg2) {
out.println(msg1);
// empy row
out.println("");
out.println(msg2);
}
The user enters a message, and this is sent to the server. Then, the server responds with N messages.
After the first request, the client stops and is never printed the word "END".
How do I send multiple messages at different times, with only one socket connection?
Firstly, you don't need to send an empty row, because you are sending by "line" and recieving by "line".
out.println(msg1);
out.println(msg2);
and
userInput = stdIn.readLine();
Here, userInput will only equal msg1
What I would recommend, would be not to loop on stdIn.readLine() = null, but have the client send, for example, "END_MSG", to notify the server that it will not send anymore messages.
Perhaps something like...
SERVER:
userInput =stdIn.readLine();
if(userInput.Equals("START_MSG");
boolean reading=true;
while(reading)
{
userInput=stdIn.readLine();
if(userInput.Equals("END_MSG")
{
//END LOOP!
reading = false;
}
else
{
//You have received a msg - do what you want here
}
}
EDIT:CLIENT:
private void sendMessage(String msg1, String msg2) {
out.println("START_MSG");
out.println(msg1);
out.println(msg2);
out.println("END_MSG");
}
(It also looks like in your question to have mixed up the client and the server?)

How to return condition in a switch statement to while?

How to return action to while loop in a switch statement ? The client is unable to return to while statement. I meant to say, whenever response comes from server, the client must start from while loop again, so that client can select his choices. Is it a problem of System.out ? (Note: It's a copied code from others) Here are the client and server :
Client:
.............
while (true) {
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
..........
case 2: // for viewing files in the client's directory
try{
Socket mysoc = new Socket("localhost", 9001);
String user_name = username;
DataOutputStream ToServer = new DataOutputStream(mysoc.getOutputStream());
ToServer.writeBytes(user_name + '\n');
BufferedReader FromServer = new BufferedReader(new InputStreamReader(mysoc.getInputStream()));
String line = null;
while ((line = FromServer.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
break;
............
}
Server:
import java.io.*;
import java.net.*;
class DirList
{
public static void main(String argv[]) throws Exception
{
String clientString;
//String replyString;
ServerSocket welcomeSoc = new ServerSocket(9001);
while(true)
{
Socket connectionSocket = welcomeSoc.accept();
BufferedReader FromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter ToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
clientString = FromClient.readLine();
System.out.println("Received view songs request from : " + clientString);
String path = "/home/sri/Songs/";
String text="";
File f = new File(path);
File[] listOfFiles = f.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
text = listOfFiles[j].getName();
ToClient.println(text);
}
}
}
}
}
Why don't you label the outermost while like this..
outer: while(true)
and use the continue keyword to return to the label.
continue outer;
try to close your PrintWriter and Socket in the Server code after they finished their task.
#Sri, about the question you've asked in the comment:
by Socket I meant connectionSocket. ServerSocket will remain there during your server life time. But you will have a new connectionSocket for each user. so each connectionSocket will serve only a single client.

Sending file list from Server to Client in java Socket programming - PrintWriter can't send?

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.

Categories