Java client server communication - java

I am trying to make a java program for client-server communication
I need to initialize a server socket and a client socket.
The server socket will accept a connection from the client.
After the connection has been accepted, the input i give to the client will be submitted to the server which will tell the client if the communication was successfull or not.
This is my code :
import java.io.*;
import java.net.*;
public class ClientServer {
public static void main(Strings args[]) throws Exceptions{
/*initialize server socket*/
Socket client_socket = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
String serverMsg = null;
while ((serverMsg = reader.readLine()) != null) {
System.out.println("Client: " + serverMsg);
ServerSocket server_socket;
server_socket=new ServerSocket(12345);
while (true) {
Socket mysocket=server_socket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
writer.write("prova\n");
System.out.printls("data sent");
}
}
}
but I need to get input from keyboard, not "from the code".
Thanks a lot.

Related

How to get Java TCP Server and Client application to loop until a certain number of requests have been made

I've written both a TCP server and a TCP client application in eclipse. The Client gets user input in the form of a string then sends it to the server who capitalizes it and sends it back. They need to keep looping until the server has received a certain number of requests in which case it closes the connection between he sockets and stops. Unfortunately it only seems to loop once. I will provide a sample output of what I'm talking about after the code.
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
do {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
outToClient.flush();
requests++;
}
while(requests < 10);
outToClient.writeBytes("REQUEST LIMIT REACHED");
}
}
}
and the client
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//Creates socket, replace the hostnmae/ip address with the ipaddress of the computer running the server application.
Socket clientSocket = new Socket("10.69.88.130", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (clientSocket.getInputStream()));
do {
System.out.print("TO SERVER: ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
outToServer.flush();
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
while (!modifiedSentence.equals("REQUEST LIMIT REACHED"));
System.out.println(modifiedSentence);
clientSocket.close();
}
}
and finally the output I'm getting
TO SERVER: testa
FROM SERVER: TESTA
TO SERVER: testb
(nothing else is displayed after this line)
Well your code is working (kind of). You get a successful run, then you restart your client without restarting the server. Your request-value does not reset to 0 and after restarting the client the first request your client does is number 10 for your server.
So why is that request comming through? Because you flush the string first and then check your counter.
I have modified your server a little bit. Maybe that is what you are looking for?
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
while (requests < 10) {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase();
outToClient.writeBytes(capitalizedSentence + " Request: " + requests + '\n');
outToClient.flush();
requests++;
}
outToClient.writeBytes("REQUEST LIMIT REACHED");
requests = 0;
}
}
}

PrintWriter won't write

I have the following problem.
I programmed a simple Echo Server and Echo Client but the problem is that in the loop of the Server, where I read from the Buffered Reader, the programme stuck and it won't write.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String message = null;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
}
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
System.out.println(message);
writer.println(message);
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
But when i put the .println() and .flush() in the loop everything works great.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
String message;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
writer.println(message);
writer.flush();
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
My question is why does it stuck in the loop ?
You are reading the inpit until end of stream before you send anything. End of stream on a socket only occurs when the peer closes the connection. The peer hasn't closed the connection, because he wants to read your reply from it.
You should echo every line as you read it, not try to assemble them all and then echo them all in one great chunk. Apart from the fact that it can't work, your technique also wastes both time and space.

Java-based 2 way chat application not working

For its partner app I switched the Client and Server code and the ports. Ran both these codes in two separate terminals. They were able to connect with each other but I was not able send message from one terminal to the other.
import java.net.*;
import java.io.*;
import java.util.Scanner;
class ChatHead1
{
public static void main()throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Client
Socket sock = new Socket("127.0.0.1", 2000);
OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
System.out.print("\nYou:");
String message1 = br.readLine(); //Inputting Message For Sending
dos.writeBytes(message1);
//Server
ServerSocket sersock = new ServerSocket(5000);
System.out.print("\nThem: ");
Socket sockServ = sersock.accept();
InputStream istream = sockServ.getInputStream();
DataInputStream dstream = new DataInputStream(istream);
String message2 = dstream.readLine();
System.out.println(message2); //Printing Received Message
//Client Close
dos.close();
ostream.close();
sock.close();
//Server Close
dstream .close();
istream.close();
sockServ.close();
sersock.close();
}
}
I would suggest that you should only use one Server/Client, because its a two way connection.
I dont really see why you are using a Client and a Server.
Try dos.flush(); after dos.writeBytes(message1);

Sending more than 1 message to TCP server in same connection

I've created a TCP Server in Java and a TCP client in Ruby. The problem is I'm not able to send more than 1 message in the same connection, Only the first message is sent while the other one is not sent.
here is the Java code
package com.roun512.tcpserver;
import java.io.*;
import java.net.*;
public class Program {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while(true)
{
Socket connection = Socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
And here is the client code
Client.rb
require 'socket'
class Client
def initialize()
server = TCPSocket.open("127.0.0.1", 6789)
if server.nil?
puts "error"
else
puts "connected"
end
server.puts("Hello\r\n")
sleep 2
server.puts("There\r\n")
server.close
end
end
Client.new()
I'm only receiving Hello. I have tried many other ways but none worked.
So my question is how to send more than 1 message in a single connection, Any help would be appreciated :)
Thanks in advance!
Socket.accept() waits for new connection after reading the first line.
Try the following:
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while (true)
{
Socket connection = Socket.accept();
while(true)
{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
If it works, change while (true) to some meaningful condition and don`t fotget to close the connection after the work is done.

Bufferedreader never null, while loop won't terminate

I'm making a program where a client uses a proxy to ask a server to retrieve content from an URL, so for example, the client types in "http://www.google.ca", and they get the html code from that webpage. I got it to work once, but I want to it work multiple times. I tried using loops but they never terminate, bufferedreader never seems to = null for the Proxy or Client class (the Server class works fine though). Any help would be greatly appreciated.
Here is my code
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception {
Client serv = new Client();
serv.run();
}
public void run() throws Exception {
Socket sock = new Socket("localhost", 7777); //connects to Proxy
PrintStream ps = new PrintStream(sock.getOutputStream()); //output stream to Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream()); //input stream from Proxy
BufferedReader br = new BufferedReader(ir);
Scanner scanner = new Scanner(System.in); //take input from keyboard
//user types in an URL, outputs content of URL
for(int i = 0; i < 100; i++) {
ps.println(scanner.nextLine());
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
scanner.close();
}
}
Proxy.java
import java.net.*;
import java.io.*;
public class Proxy {
public static void main (String[] args) throws Exception {
Proxy serv = new Proxy();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(7777);
Socket sock = ss.accept();
//input and output streams to and from Client
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToClient = new PrintStream(sock.getOutputStream());
//input and output streams to and from Server
Socket sck = new Socket("localhost", 8888);
PrintStream ps = new PrintStream(sck.getOutputStream());
InputStreamReader irFromServer = new InputStreamReader(sck.getInputStream());
BufferedReader brFromServer = new BufferedReader(irFromServer);
//passes message from Client to Server, passes URL content from Server back to Client
for(int i = 0; i < 100; i++) {
String message = br.readLine();
ps.println(message);
System.out.println("Client wants me to tell Server he wants the content of: " + message);
String inputLine;
while((inputLine = brFromServer.readLine()) != null) {
psToClient.println(inputLine);
//psToClient.flush();
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
ss.close();
sck.close();
}
}
Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main (String[] args) throws Exception {
Server serv = new Server();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(8888);
Socket sock = ss.accept();
//input and output streams to and from Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToProxy = new PrintStream(sock.getOutputStream());
//retrieves content from requested URL and sends back to Proxy
for(int i = 0; i < 100; i++) {
String request = br.readLine();
System.out.println("Proxy told me Client wants the content from: " + request);
//makes URL object using String value from Client
URL url = new URL(request);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
//sends URL content back to Client, via Proxy
String inputLine;
while ((inputLine = in.readLine()) != null) {
psToProxy.println(inputLine);
//psToProxy.flush();
System.out.println(inputLine);
}
System.out.println("FINISHED SENDING CONTENT");
in.close();
}
sock.close();
ss.close();
}
}
bufferedreader never seems to = null
Your question is a little imprecise. What you mean is that BufferedReader.readLine() never returns null. That only happens when the peer closes the connection. If he never closes it, readLine() won't return null.
If you're writing an HTTP proxy you need to have a good look at RFC 2616, and specifically the requirements about the Content-length header, the Connection: close header, and chunked transfer encoding. Just reading the response stream to its end is in general not sufficient.

Categories

Resources