how to send TCP Requests in java - java

I am using Sockets to connect using TCP and I want to make different calls. e.g. Get InputValue
I have these type of different requests which I want to make from already running server.
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
String func="Get inputvalue";
byte[] tRequest = encoder.string2bytes(func);
out.write(tRequest);
out.flush();
System.out.println("write done");
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
It says it connected as just connected printout got printed. Write done print is also printed but no data is returned and the program keeps on running.
If I use telnet then this same request call returns data successfully.
So the question is how to make TCP calls in java?
Update: I solved this by:
PrintWriter toServer =
new PrintWriter(client.getOutputStream(),true);
BufferedReader fromServer =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
toServer.println("Get inputvalue\r\n");
String line = "";
System.out.println("Client received: ");
while ((line = fromServer.readLine()) != null) {
System.out.println(line);
}
but the program keeps on running in the while loop and prints nothing. how to check that response is ended?

Related

Java Socket Client not Recieving Data

I have created my first test application implementing a socket server. I am having some issues getting the client to receive data, but the server gets data just fine. Here is the server:
ServerSocket socket = new ServerSocket(11111);
System.out.println("CREATING SERVER...");
while (true) {
Socket SERVER_WORK = socket.accept();
BufferedReader clientIN = new BufferedReader(new InputStreamReader(SERVER_WORK.getInputStream()));
PrintWriter outSend = new PrintWriter(SERVER_WORK.getOutputStream());
String ClientSTR = clientIN.readLine();
System.out.println("Client 1: " + ClientSTR);
String toClient = "Hello";
outSend.write(toClient + '\n');
}
And here is the client:
System.out.println("CONNECTING TO SERVER...");
while (true) {
Socket clientSocket = new Socket(server, 11111);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream toServere = new DataOutputStream(clientSocket.getOutputStream());
Scanner in = new Scanner(System.in);
toServere.write(in.nextLine().getBytes());
if (fromServer.ready())
System.out.println(fromServer.readLine());
clientSocket.close();
}
Everything works properly except for the client receiving data.
I found the solution: I needed a '\n' at the end of the line for the DataOutputStream/PrintWriter for the BufferedReader to work properly.

Client-Server communication with BufferedReader hanging

I'm testing around with client-server communication.
I have a server that should receive messages and print them, and send messages that it gets from System.in using a Socket. The client reads messages from the Socket, and sends back some messages. But for some reason both the server and the client get locked when checking if there is a message from the other end (at readLine()).
This client:
public void run() {
try {
Log.i("DataManager", "Trying to connect to server");
socket.connect(new InetSocketAddress(ADDRESS, PORT), 3000);
Log.i("DataManager", "Connected to: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
while (socket.isConnected()) {
if ((inputLine = in.readLine()).isEmpty()){
Log.i("DataManager", "Server says: " + inputLine);
}
synchronized (outcoming){
if (!outcoming.isEmpty()){
for (int i = 0; i < outcoming.size(); i++){
out.println(outcoming.get(i));
outcoming.remove(i);
}
}
}
}
}
...
}//
The Server:
ServerSocket listener = new ServerSocket(PORT);
try {
Socket socket;
socket = listener.accept(); //waits for connection
System.out.println("Client connected: " + socket.getInetAddress());
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader clientIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
out.println("Hello, you are connected to server" + listener.getInetAddress());
while (true){
if ((inputLine = clientIn.readLine()).isEmpty()){
System.out.println("Client says: " + inputLine);
}
String line = sysRead.readLine();
if (line.equals("stop")){
break;
} else {
out.println(line);
}
}
socket.close();
}
I tried solving this by encasing the readLine statements with if(in.ready()) but it didn't help at all. I've been looking around on google and found that this is caused by the fact that readLine() looks for eof, and the stream from the socket only ends when the socket is disconnected. I have no idea how to get around this problem other that writing some kind of protocol where i end my messages with a specific sequence. Is there a better way around this problem?

Client/Server Program in Java - Streams

I have a problem getting the output that i want from the code that i have implemented in order to create the server/client program...it's just a really simple one, and i don't know why i don't get what i want.
Here is the code of the server:
ServerSocket serverSocket = new ServerSocket(1025);
System.out.println("Porting...");
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = in.readLine();
System.out.println("Server read: " + s);
out.write("Got it");
socket.close();
System.out.println("Server Exit");
The client:
System.out.print("Connecting...");
Socket socket = new Socket("localhost",1025);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.write("Hello, Server");
String s = in.readLine();
System.out.println("Client Recieved: " + s);
socket.close();
System.out.println("Client Exit");
I try to get the Hello, Server output, instead i just get the "connecting" syso from the client (which i just did to see if it works)
Once you wrote on the stream you have to flush the stream by calling flush() method on the outputstream. Else the stream will be flushed once the stream buffer is full.
out.flush();
Also you have to make sure that enter the new line character to mention the end of line. Because readLine() waits for string with newline().
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r')
out.write("Hello, Server\n");
out.flush();

Socket Server will not receive properly

I am trying to make a socket server, I am connecting through putty to this server. Whenever I type "hi" it says "no" rather than "hi" which I want it to do. I found this on A java website. If you could tell me what I am doing wrong that would be great. Thanks!
int port = 12345;
ServerSocket sock = new ServerSocket(port);
System.out.println("Server now active on port: " + port);
Socket link = sock.accept();
System.out.println("Interface accepted request, IP: " + link.getInetAddress());
BufferedReader input = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
output.println("ISEEYOU");
String inputLine;
Thread.sleep(1500);
while((inputLine = input.readLine()) != null) {
if(inputLine.equals("hi")) {
output.println("hi");
}else{
output.println("no");
}
}
Your Java program is correct.
I've tried your code, just added System.out.printf("[%s]", inputLine); as first line in the while loop to ensure, what I get from putty.
I guess your problem is the protocol putty uses to connect. It worked with RAW for me. See below the session setting I've used:
EDIT:
According to your comment I added some code for a simple client, that reads the line from console, sends it to the server and prints the echo back to console.
public void Client() throws IOException {
// Client that closes the communication when the user types "quit"
Socket socket = new Socket("localhost", 8080);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!(line = user.readLine()).equals("quit")) {
ps.println(line); // Write to server
System.out.println(reader.readLine()); // Receive echo
}
socket.shutdownOutput(); // Send EOF to server
socket.close();
}
The corresponding server would look like this:
public void server() throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
// Just read a line and echo it till EOF
String line;
while((line = reader.readLine()) != null) ps.println(line);
}
You might need to change the port I used here, if 8080 is already binded on your machine. Also you might want to have the server running on another computer then the client. In this case you need to change "localhost".

Send string to client upon command JAVA

So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break

Categories