I have a java client program that sends a command to server and server sends back an acknowledgement and a response string.
My client program gets the input stream length from client socket as
0. But, I used wireshark to investigate. Wireshark logs show that the server has sent back a response to my ip. Somehow, my client is unable
to read it.
My Client
public class Client {
private static final String SERVER_ADDRESS = "192.168.64.79";
private static final int TCP_SERVER_PORT = 6669;
public void connect(String command) {
BufferedReader in;
try {
// Socket skt = new Socket("50.128.128.254", 6669);//ip,port
Socket clientSocket = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);// ip,port
System.out.println(" client Socket created ..Enter command : ");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
String ToServer = command;
outToServer.println(ToServer);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("Received string : length "+clientSocket.getInputStream().available()+"\n response:");
// while (!in.ready()) {
// }
System.out.println(in.readLine()); // Read one line and output it
// System.out.print("'\n");
in.close();
clientSocket.close();
System.out.print("connection closed");
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n");
e.printStackTrace();
}
}
}
WireShark results:
9bytes of data sent from server to my client
Client output
Java client receives inputstream length 0
Related
I have the following server called Server.class and what exactly does, it receives text from the client and then sends that exact text back to the client. I'm just learning and I used the server from this website http://www.javaworld.com/article/2077322/core-java/core-java-sockets-programming-in-java-a-tutorial.html.
The Client in my case is the browser so i don't need to implement it.
What I want to get is when a client asks for a file like: localhost:8888/myfile.txt
I should give him back that file, so he can download it or see it from the browser.
I tried to use a BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
is is a variable from InputStream
So now i can know what the client introduced doing String clientData = br.readLine()
But how can I get the file (myfile.txt) from that string and return that file so it can be observed or downloaded in the browser??
The Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String args[]) {
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 8888
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(8888);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
If I make a socket connection from an application that is running on an application server, where does the returned data go? Is it necessary to create a receiving server socket in the application with a specified port, or is it received on the port at which the server is using to connect to the application and I just need to write something that will extract that data?
Here is the code to read from a socket. You are making socket connection to port 8080 in server. You don't have to worry about the OS -> Server port.
public static void readSocket() throws IOException {
try (Socket s = new Socket(InetAddress.getByName(new URL("Some Address").getHost()), 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
}
The socket is one end-point of two-way communication link between server and client programs of the network.
The returned data is sending to your client Socket object, lets call it clientSocket. You need to call clientSocket.getInputStream() to decode it.
No, you dont need to create a receiving server socket in the application. Your client program establishes a connection to the server on your given host and port. clientSocket can both send data to server and receive data from server.
For example the client side code:
private PrintWriter out = null;
private BufferedReader in = null;
public void listenSocket(){
//Create socket connection
try{
clientSocket = new Socket(HOST, PORT);
// use out object to send data to server applicaiton
out = new PrintWriter(clientSocket.getOutputStream(),
true);
// uses in object to receive data from server application
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + HOST);
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
I'm having the following TCP client code:
public static void register(InetAddress ip, int port, String name) {
try {
Socket clientSocket = new Socket(ip, port);
send("reg:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send(String str) {
try {
String sentence = str;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence);
} catch (IOException e) {
Log.e("CONNECT", e.getMessage());
}
}
They both are called in onClicks and i know that for sure.
I also have the following Server code:
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9876);
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);
outToClient.writeBytes("msg: Hello! kalin pedro");
}
}
When trying to send data to the server i don't get an exception, i also know that I'm connected to it because the application is crashing when i terminate the server application. The problem is that the server doesn't receive anything until i terminate the client application. Everything that i have tried to send until that moment is all received from the server at once. I looked at the network activity tab provided by Android Studio and there is a change when sending data, the server just doesn't receive it(or at least i don't see it receive it) until i terminate the client application.
I am trying to establish communication between a SocketServer (Server) in Java and a Socket (Client) in php.
The client is able to connect to host, the client is able to send a message and the server reads the message successfully. But the problem arises when the SocketServer writes to the Client, the client does not receive the message from the server.
I have read the other questions on the same scenario (java-php socket communication) but i just can't seem to find what is causing the problem.
If i use a Java Socket as a client the communication works perfectly both ways.
The Server :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
protected ServerSocket socket;
protected final int port = 9005;
protected Socket connection;
protected String command = new String();
protected String responseString = new String();
public void init(){
System.out.println( "Launching Server: " );
try{
socket = new ServerSocket(port);
while(true)
{
// open socket
connection = socket.accept();
System.out.println( "Client Connected " );
// get input reader
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
// get input
command = input.readLine();
// process input
System.out.println("Command: " + command);
responseString = command + " MC2 It Works!";
// get output handler
PrintStream response = new PrintStream(connection.getOutputStream());
// send response
response.println(responseString);
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
The Client :
class Client {
private $address;
private $port;
public function __construct($address, $port){
$this->address = $address;
$this->port = $port;
$this->init();
}
private function init(){
//create socket
if(! $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))){
$this->showError("socket create");
};
//establish connection
socket_connect($socket, $this->address, $this->port);
//write to server
$message = "I am a client";
socket_write($socket, $message, strlen($message)); //Send data
echo "Listening to Server\n";
//read from server
if(!$reponse = socket_read($socket, 2048, PHP_NORMAL_READ)){
$this->showError("socket read");
}
//print response
echo "Response from server------------------\n";
echo $reponse;
socket_close($socket);
}
private function showError($message){
echo ("Error: ".$message);
exit(666);
}
}
$address="localhost";$port=9005;
echo "Testing Client Server\n";
$client = new Client($address, $port);
Could someone please guide me to what could be the problem here ?
In server side, the code expects a line(terminated with linefeed), in php You send
socket_write($socket, $message, strlen($message));
Please check the data you send accordingly making sure that you send the linefeed character.
There's a million examples on using Java sockets out there - and every one is the same!
Every one shows a client socket being created, some text being sent, and the socket closed.
I am writing some test code. I want my client to loop round and send quite a few messages. It seems silly to close the client socket each time and re-create, so I thought I would just create one client socket, loop round and send data on the same socket. The thing is though - my server socket does not print out what it has received until the last message has been sent by the client and the client socket closed.
Server:
Socket sock;
ClientConnection client;
ServerSocket ss = new ServerSocket(portNumber);
ss.setSoTimeout(0); // 0=infinite
while (true) {
sock = ss.accept();
client = new ClientConnection(sock);
new Thread(client).start();
// ClientConnection reads from sock, prints, and closes sock
}
ClientConnection (a separate class on the Server side):
public class ClientConnection implements Runnable
{
private Socket m_socket;
private BufferedReader m_in = null;
public ClientConnection(Socket socket)
{
m_socket = socket;
try {
InputStream inStream = socket.getInputStream();
m_in = new BufferedReader(new InputStreamReader(inStream));
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public String getMessage()
{
String line = null;
StringBuffer completeMessage = new StringBuffer();
try {
while ((line = m_in.readLine()) != null)
{
completeMessage.append(line);
}
}
catch (IOException ioe) {
ioe.printStackTrace();
return "";
}
return completeMessage.toString();
}
public void run()
{
try {
String message = getMessage();
System.out.println("Received: " +message);
}
finally
{
try {
m_socket.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Client:
socket = new java.net.Socket(m_destination, m_portNumber);
outputStream = socket.getOutputStream();
printStream = new java.io.PrintStream(outputStream);
while (more-stuff-to-send)
{
printStream.print(text);
printStream.print("\n");
printStream.flush();
}
prinStream.close();
socket.close();
ClientConnection is created by the server when I start the client, but it does not print what has been sent until the client is done sending.
I feel like I'm missing the point somewhere along the line. Chat examples are quite common, so if I had a chat client then every message it wanted to send to a chat server it would create a client socket, send the message, and close the socket? Just doesn't seem right somehow.
Thank you.
client = new ClientConnection(sock);
You are passing the socket in constructor.
so you shouldn't do:
socket = new java.net.Socket(m_destination, m_portNumber);
just cache that vatiable from contructor as : this.sock = sock;
getting the reader and the writer is ok, also the server is ok.
I would use a Vector to be synchromized queue for sending messages, and the while (more-stuff-to-send) loop would check the queue and id empty than sleep, if has something to send, than pop the first and sent it while he must do stuff, or socket is closed my the client.