Unable to continuously send data between tcpserver and tcpclient in java - java

My TCP Client does not seems to be able to receive the data send from server after the connection is being accepted by the server.
I made the client initiate the connection, and I like it to work in this way.
loop:
client --> Server;
client <-- Server;
I am new to Java TCP socket programming, could somebody please enlighten me on how to make them work properly. Thanks and Appreciate help given in advance.
TCP Client Code:
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true)
{
System.out.println("Message:");
sentence = inFromUser.readLine();
if(!sentence.equals("exit"))
{
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine(); //It does not receive any data from server.
System.out.println("FROM SERVER: " + modifiedSentence);
}
else
{
outToServer.writeBytes(sentence + '\n');
clientSocket.close();
break;
}
}
}
}
TCP Server Code:
import java.io.*;
import java.net.*;
import java.util.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String serverSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
Socket connectionSocket;
connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
while(true)
{
clientSentence = inFromClient.readLine();
if(!clientSentence.equals("exit\n"))
{
System.out.println("Received: " + clientSentence);
System.out.println("Message:");
serverSentence = inFromUser.readLine();
outToClient.writeBytes(serverSentence); //able to send, but client is not receiving.
}
else
{
connectionSocket.close();
welcomeSocket.close();
}
}
}
}

Try to flush the data:
outToClient.writeBytes(serverSentence); //able to send, but client is not receiving.
outToClient.flush();

In the client you are closing the socket after sending data to the server. You need to keep it open.
while(true)
{
System.out.println("Message:");
sentence = inFromUser.readLine();
if(!sentence.equals("exit"))
{
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine(); //It does not receive any data from server.
System.out.println("FROM SERVER: " + modifiedSentence);
}
else
{
outToServer.writeBytes(sentence + '\n');
clientSocket.close(); //socket gets closed. Reopen it on the server side or remove that line
break;
}
}

After outToServer.writeBytes(sentence + '\n'); do outToServer.flush();
After outToClient.writeBytes(serverSentence + '\n'); do outToClient.flush();

Related

Cannot get response from java server app

I have the following code below which is a very basic server. In the browser I put something like: localhost:6789/xxxx. When the app is running it does read the request from the client but then the message "This site can’t be reached" is displayed and the app throws an exception. What is the best way to respond to the client?
import java.net.*;
import java.io.*;
import java.net.Socket;
public class URLConnection {
public static void main(String[] args)throws IOException {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
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("HTTP/1.1 200 OK");
}
}
}
You have to close the OutputStream:
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("HTTP/1.1 200 OK");
outToClient.close();
}
Be aware that
the request may not necessarily be HTTP 1.1, and thus your response would be invalid.
there will actually be several clientSentence (i.e. consider adding a loop as below)
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while(true) {
clientSentence = inFromClient.readLine();
if (clientSentence != null && clientSentence.trim().isEmpty()) {
break;
} else {
System.out.println("Received: " + clientSentence);
}
}
outToClient.writeBytes("HTTP/1.1 200 OK\n\nHello world");
outToClient.close();

TCP Server only receives one message

I am trying to create a simple TCP server and client. I want the client to be able to send multiple messages by only opening the socket once. I have looked at similar questions here, here, and here but they haven't been much use.
My code is a follows:
SampleServerTCP.java
public class SampleServerTCP {
private static final int DEFAULT_PORT_NUMBER = 39277;
public static void main(String[] args) throws IOException {
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}
}
}
TCPClientTest.java
public class TCPClientTest {
public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
Socket clientSocket = new Socket("localhost", 39277);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
int c = 0;
while(c<10){
outToServer.writeBytes(c + "\n");
outToServer.flush();
c++;
Thread.sleep(500);
}
clientSocket.close();
}
}
The only output I get is:
Listening on port: 39277
Recieved: 0
Where am I going wrong?
Your problem lies here:
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}
You are opening the socket, reading only one line and then you are waiting for the next socket.
Instead you should do Socket connectionSocket = defaultSocket.accept(); outside your while loop, and read from this socket in your loop, like this:
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = "";
while ((msg = fromClient.readLine()) != null){
System.out.println("Recieved: " + msg);
}
Change your server side code like below
public class SampleServerTCP {
private static final int DEFAULT_PORT_NUMBER = 39277;
public static void main(String[] args) throws IOException {
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);
System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();;
while (msg!=null){
System.out.println("Received: " + msg);
msg = fromClient.readLine();
}
}
}

Client Server Application Not Working

I am trying to write a simple client/server Echo application, my client seems to be sending the input, but the server doesn't seem to pick it up and send it back.
Here's the server:
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws Exception
{
int port = 2000;
ServerSocket serverSocket;
Socket client;
BufferedReader is = null;
BufferedWriter os = null;
serverSocket = new ServerSocket(port);
System.err.println("Server established on port " + port);
client = serverSocket.accept();
System.err.println("Client connected");
is = new BufferedReader(
new InputStreamReader(client.getInputStream()));
os = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
System.err.println("Server established on port " + port);
String message = "";
while((message = is.readLine()) != null)
{
System.err.println("Messaged received " + message);
os.write(message);
}
is.close();
os.close();
serverSocket.close();
}
}
Then, the client looks like this:
import java.io.*;
import java.net.Socket;
public class Client
{
public static void main(String args[]) throws Exception
{
String host = "localhost";
int port = 2000;
Socket socket;
socket = new Socket(host, port);
BufferedReader is = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter os = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
System.err.println("Connected to " + host + " on port " + port);
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input = "";
while((input = br.readLine()) != null)
{
System.out.println("Sending " + input);
os.write(input);
System.out.println("Receiving " + is.read());
}
is.close();
os.close();
socket.close();
}
}
What am I missing, I am sure I overlooking something simple.
In the client, try writing the message with a final newline char:
os.write(input+"\n");
(or call also newLine())
That because the server is reading line-by-line.

server/client chat socket in java

I have a server/client socket connection, each side can send a message to the other. The client who must begin the chat. I want to close the connection when one of the both sides (server and client) sends "quit" message.
here is my code:
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
while(true){
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
if(modifiedSentence.equals("quit\n")) clientSocket.close();
}
}
}
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String sentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
ServerSocket welcomeSocket = new ServerSocket(6789);
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("FROM CLIENT: " + clientSentence);
//capitalizedSentence = clientSentence.toUpperCase() + '\n';
sentence = inFromUser.readLine();
outToClient.writeBytes(sentence);
}
}
}
Any help? :)
You have already written one line. Write another for "quit" and check this string when reading and close().
if you don't understand what you program is doing, use your debugger, that is what it is for.

java DataOutputStream exception

The exception is thrown in line 24 the second time I type something (after I have typed the host name) - server works right. Code
import java.io.*;
import java.net.*;
class TCPclient {
public static void main(String[] args) throws Exception {
String hostname, msg;
InetAddress hostaddress;
BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Please type host\n");
hostname = inFromUser.readLine(); //I type localhost
hostaddress = InetAddress.getByName(hostname);
Socket cSocket = new Socket(hostaddress, 44444);
String cAddress = cSocket.getLocalSocketAddress().toString();
DataOutputStream outToServer = new DataOutputStream (cSocket.getOutputStream());
while (true)
{
msg = inFromUser.readLine();
System.out.println(msg);
if (msg.equals("exit"))
{
System.out.println("exit");
break;
}
outToServer.writeBytes(cAddress + " said : " + msg + '\n'); //this line throws an exception the second time it runs
}
cSocket.close();
}
}
I am new in java so I am missing something obvious I guess. Exception reads :
Exception in thread "main"
java.net.SocketException: Software
caused connection abort: socket write
error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
at TCPclient.main(TCPClient.java:52) Java
Result: 1
Server :
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );
clientSentence = inFromClient.readLine();
System.out.println(clientSentence + "\n");
}
}
}
Your client creates one socket and writes over and over again to that one socket. Your server, on the other hand, does this:
ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
That accepts the incoming connection, reads one line, and then abandons it (and I'm guessing on the socket's finalize when being garbage collected it closes the connection). Then it waits for a new connection.
So to fix your immediate problem, try moving
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );
before the while loop.
How long do you wait between typing second line? It might have something to do with socket being idle.
Also with the server code like this you will see only first message. Try this:
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(44444);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
while (true) {
clientSentence = inFromClient.readLine();
System.out.println(clientSentence + "\n");
}
}
}
Try:
while (true)
{
if(inFromUser.readLine() != null)
{
msg = inFromUser.readLine();
System.out.println(msg);
if (msg.equals("exit"))
{
System.out.println("exit");
break;
}
outToServer.writeBytes(cAddress + " said : " + msg + "\n");
}
}
Note the changes:
if(inFromUser.readLine() != null)
{
and
... "\n");
not
... '\n');
Give it a shot. It's probably too simple a solution, but it's something :)

Categories