TCP stream being read by Java - java

I would like to create a Java server socket application that receives a TCP packet and reads the content of it. Based on the contents of the packet it will perform several actions. I managed to get to the point where it reads some content and prints a string System.out.println(sb.toString());
But (a) not all the content is printed and (b) I am not sure how to process the content as they arrive in network order. An example would be to receive an HTTP packet and from the header to report the "Content-Length" or the "User-Agent". Any example would be appreciated.
public static void main(String[ ] args){
PrintWriter out = null;
BufferedReader in = null;
int bufferSize = 0;
try{
String message = args[0];
int count = 0;
ServerSocket connectionSocket = null;
try {
connectionSocket = new ServerSocket(4444);
System.out.println("Server started");
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
while(true){
count++;
clientSocket = connectionSocket.accept();
System.out.println("TCP packet received… " + count);
InputStream is = clientSocket.getInputStream();
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
clientSocket.close();
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
}
catch(Exception e){
e.printStackTrace();
}
}

Related

Java Socket: Server won't read input until client server is closed -> Server can't response to client

I'm trying to make a basic client <-> server connection in Java. When trying to write to the server, the client sends the details correctly, and the server stalls on reading it until the client output stream is closed. Though, once the output stream is closed it apparently closes the socket, and due to that the server can't reply to the client. Here's the main snippet of code that handles this interaction.
Client:
private void sendCmd(String cmd) {
String infoToSend = cmd;
try {
socket = new Socket(hostname, port);
System.out.println("Trying to send: " + com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out.flush();
System.out.println("Socket is flushed");
System.out.println("Waiting for Data");
InputStream is = socket.getInputStream();
System.out.println("Trying to get data");
BufferedReader input = new BufferedReader(
new InputStreamReader(is)
);
String line;
while((line = input.readLine()) != null) {
System.out.println(line);
}
socket.close();
} catch (IOException e) { e.printStackTrace(); }
}
Server:
public void run() {
System.out.println("Got Connection");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
String response;
System.out.println("Response:");
String decode = "";
while ((response = in.readLine()) != null) {
try {
decode = new String(Base64.decode(response));
} catch (Base64DecodingException e) {
e.printStackTrace();
}
}
System.out.println("Decoded: " + decode);
out.writeBytes("We got your message!");
out.flush();
out.close();
} catch (IOException e) { System.out.println("Fail"); e.printStackTrace(); }
Would anyone be able to guide me on how to fix this error. Sorry if it's super easy and I'm just unable to see it.
Sending
socket.shutdownOutput();
solved the issue.

Socket android framework doesn't send message

I'm trying to add a client socket in the file ViewRootImpl.java. I'm creating the socket in a new thread with an handler because I need to comunicate between threads. I'm sending a message to Vthread every time performTraversal is called.
Client code in ViewRootImpl.java:
public class Vthread extends Thread{
Viewhandler mViewhandler;
Handler mhandler;
Socket client;
BufferedReader in;
PrintWriter out;
String s;
String line;
Vthread(Viewhandler handler){
mViewhandler = handler;
in = null;
out = null;
s = "hello";
client = null;
}
#Override
public void run(){
Looper.prepare();
try{
client = new Socket("10.0.2.2", 60000);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
mhandler = new Handler(){
#Override
public void handleMessage(Message msg) {
try{
if(out != null && in != null && client != null){
out.println(s);
out.flush();
line = in.readLine();
}
}catch (IOException e) {
e.printStackTrace();
}
}};
Looper.loop();
}
}
The server code in the host:
Socket socket;
ServerSocket server;
SocketAddress sockaddr;
BufferedReader in = null;
PrintWriter out = null;
String line;
String s = "bye";
server = null;
try{
sockaddr = new InetSocketAddress("127.0.0.1", 60000);
server = new ServerSocket();
server.bind(sockaddr);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}catch (IOException e) {
e.printStackTrace();
}
try{
System.out.println("connected");
while(!Thread.currentThread().isInterrupted()){
line = in.readLine();
System.out.println(line);
out.println(s);
}
if (server != null ) server.close();
}catch (IOException e) {
e.printStackTrace();
}
The connection is accepted but the server doesn't receive any message from client. A problem that I identified is that more than one process might be using the socket. So I used a file in the internal storage of my application to restric the socket to my application only, but the problem remains. Code to restrict the socket to my application:
if(mVthread.mhandler != null) {
try{
if(reader == null) reader = new BufferedReader(new FileReader(file));
Message msg = Message.obtain();
msg.arg1 = 1000;
mVthread.mhandler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
EDIT
The problem is that the client socket sends a message but the server doesn't receive it. Both sides are blocked in the receive function. Any idea on what I am doing wrong?

Socket Java - Client receives a wrong information

I am trying to send two numbers via Socket. The Server receive the numbers and I make some calculation, but when I send back to Client the result, the Client receive a number which he send it.
Where I doing wrong beceause I don't understand?
Client.java
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25010;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String number2 = "5";
String sendMessage = number + "\n";
String sendMessage2 = number2 + "\n";
bw.write(sendMessage);
bw.write(sendMessage2);
bw.flush();
System.out.println("Message sent to the server:\n" + sendMessage + sendMessage2);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " + message);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Server.java
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25010;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port " + port);
ArrayList<String> arr = new ArrayList<String>();
//Server is running always. This is done using this while(true) loop
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null) {
out.println(inputLine);
arr.add(inputLine.trim());
}
System.out.println("Message received from client is:");
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
//Return message
String returnMessage = null;
try {
int numberInIntFormat = 0;
int num = 1;
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
numberInIntFormat = Integer.parseInt(arr.get(i));
num = num * numberInIntFormat;
}
arr.clear();
returnMessage = String.valueOf(num);
} catch(NumberFormatException e) {
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
bw.write(returnMessage);
bw.flush();
System.out.println("returnMessage = " + returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e) {}
}
}
}
Your server code echoes everything it reads from the client back to the client before it does anything else with it:
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null) {
out.println(inputLine); // <-- HERE
arr.add(inputLine.trim());
}
It is unsurprising that the client receives what the server sent.
Try this:
Client:
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25010;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String number2 = "5";
String sendMessage = number + "\n";
String sendMessage2 = number2 + "\n";
bw.write(sendMessage);
bw.write(sendMessage2);
bw.newLine(); // You need to send a special line for say to the server: "Hey, I have done";
bw.flush();
System.out.println("Message sent to the server:\n" + sendMessage + sendMessage2);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " + message);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Server:
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25010;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port " + port);
ArrayList<String> arr = new ArrayList<String>();
//Server is running always. This is done using this while(true) loop
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null && inputLine.length() > 0) { // You need to stop loop when you get empty line
// out.println(inputLine);
arr.add(inputLine.trim());
System.out.println("Message received from client is:"+inputLine.trim());
}
System.out.println("Message received from client is:");
//Return message
String returnMessage = null;
try {
int numberInIntFormat = 0;
int num = 1;
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
numberInIntFormat = Integer.parseInt(arr.get(i));
num = num * numberInIntFormat;
}
arr.clear();
returnMessage = String.valueOf(num);
} catch(NumberFormatException e) {
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
bw.write(returnMessage+"\n"); // You need to add '\n' otherwise readLine never gets;
bw.flush();
System.out.println("returnMessage = " + returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e) {}
}
}
}
String inputLine;
while ((inputLine = br.readLine()) != null) {
arr.add(inputLine.trim());
}
With this change, the output is:
Server:
Server Started and listening to the port 25010
Client:
Message sent to the server:
2
5
And now the Server is 'blocked' in while loop and the Client don't recive any feedback.
I found a better method:
while (br.ready() && (inputLine = br.readLine()) != null)
This tell that to read the buffer if it is something to read.
With the response from #John Bollinger, the buffer read only up to first line break, so if you try to parse a String which contains a line break, you will get out when appear the line break.
With br.ready() it will parse all the String and will get out at the end of buffer.

Java Sockets: Sending Stdin and GUI data from Client to Server, Server not reading and responding as expected

Apologies as I asked something similar last night, but I have narrowed my problem down. I am wondering how to make my Java TCP Socket Server read in the data sent using the printWriter(out) in the Client code from a GUI as it does from the command line stdin.
I have the following classes as an example and everything works fine until the GUI comes into the equation. The data is being sent over to the Server from the GUI as I can echo it on the server side, but it is not being read and parsed properly as the stdin is. Nothing is being sent back to the client. I have tried flushing, using different streams and adding line separators all over the place to no avail. There is also a Protocol class that handles the data on the Server side.
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Waiting for client...");
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
.
public class KnockKnockClient {
public static PrintWriter out = null;
public static String sendAnswer;
public static void Client() {
//JButton Action Listener
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
String data = "รท" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
KnockKnockClient.Client();
Socket kkSocket = null;
//PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}

Cannot send commands via Sockets

I'm new to the world of Java and now I'm trying to create a socket program. I created a server and a client, but they didn't seem to work. Now I post the code.
This is the server:
import java.net.*;
import java.io.*;
public class TCPCmdServer
{
public int port;
public ServerSocket server;
TCPCmdServer (int port)
{
this.port = port;
if(!createServer())
System.out.println("Cannot start the server");
else System.out.println("Server running on port " + port);
}
public boolean createServer ()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdServer tcp = new TCPCmdServer(5000);
boolean flag = true;
while (flag)
{
try
{
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
String cmd = in.readLine();
System.out.println("Recieved: " + cmd);
if (cmd.equals("END"))
{
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
flag = false;
}
else
{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null)
{
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
And this is the client:
import java.net.*;
import java.io.*;
public class TCPCmdClient
{
public Socket socket;
public int port;
public String ip;
TCPCmdClient (String ip, int port)
{
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else System.out.println("Connected to " + ip + ":" + port);
}
public boolean createSocket ()
{
try
{
socket = new Socket(ip, port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try
{
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag)
{
System.out.println("Type a command... type END to close the server");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END"))
{
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else
{
String outputline;
while ((outputline = in.readLine()) != null)
System.out.println(outputline);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
[old]
I believe the problem is with the input and output streams, but I can't understand why they don't work.
The expected behavior is as follows: The client connects to the server then the server send response. The client asks the user to insert a MS-DOS command (or a "END" command), the command is then sent to the server. The server executes the command on the computer where it is running (in case the command is END it closes the connection). Then the server sends the result of the command to the client, and the client displays it to the user.
[/old]
Now the only problem is that I have to close and re-open a client any time I like to execute a new command
In your server code, you are creating a new socket for every command you received from the client. That is why you have to open a new client every time you want to send a command to the server. To correct this, first you need to remove the while(flag) loop in server code. Then you can use the following to establish the connection to the client and send and receive command and output between them.
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
try {
while(!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null) {
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
}
In TCPCmdServer.java, try changing
out.write("Welcome on the server... type the commands you like, type END to close me");
to
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
Also, change
out.write(buffer.toString());
to
out.write(buffer.toString() + "\n");
out.flush();
In TCPCmdClient.java
change
out.write(cmd);
to
out.write(cmd + "\n");
out.flush();
response = in.readLine();
System.out.println("Server: " + response);

Categories

Resources