Java Sockets - Server hangs after client sends its response - java

Just trying to get a handle on sockets. The server and client are running in two different programs.
They seem to be connecting fine to each other but the client will not properly send its output to the server. The server just hangs. Here's the code:
Server:
private ServerSocket serverSocket;
private Socket client;
public void run() throws Exception {
serverSocket = new ServerSocket(20005);
while(currentState == Game.State.NORMAL) {
client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String clientInput = in.readLine();
// Takes the client input string and does some simple game logic that returns a Gson object
Gson serverResponse = processInput(clientInput);
out.write(serverResponse.toString());
out.flush();
}
}
Client:
Socket clientSocket;
void run() throws Exception {
clientSocket = new Socket("192.168.0.24", 20005);
PrintWriter out;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Print the state of the game - returns false if state is win or lose.
while(printState()) {
out = new PrintWriter(clientSocket.getOutputStream(), true);
// This method just takes some input from the console
String clientInput = getInput();
out.write(clientInput);
out.flush();
String serverResponse = in.readLine();
updateState(serverResponse);
}
}
}
There is some underlying game logic that is happening but it's pretty minor and should be irrelevant. I imagine I am just misunderstanding something fundamental here.
Thanks all.

Make sure you send a newline character to match the in.readLine() statement in the Server.
out.write(clientInput + "\n");
The same applys when sending data from Server->Client.

Related

How do I know If client wants to send the data or recieve the data from server

when I am trying to send the data from the server, my client side is not able to receive the data. The server is able to write the data to the JSON file. I think because I am executing the code for sending and receiving the data on the server inside the main method every time regardless of what request I am receiving from the client. Is there any built-in method in Java that helps us know what the client request is and execute the codes on the server depending on the request rather than executing the code for both read and write request. I hope You guys understand.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(666);
FileReader fileReader = new FileReader("MYJSON.json");
BufferedReader buff = new BufferedReader(fileReader);
while(true) {
Socket socket = serverSocket.accept();
InputStreamReader inputStreamReader = new
InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = bufferedReader.readLine();
writeJson(str);
String str;
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
str = buff.readLine();
printWriter.write(str);
printWriter.flush();
printWriter.close();
}
}

Java TCP Socket Programming - building large string on server to print on client [duplicate]

This question already has answers here:
Official reasons for "Software caused connection abort: socket write error"
(14 answers)
Closed 5 years ago.
I am trying to get comfortable with socket programming and wanted to write a program where a client is able to enter a website/port, pass that information to the server, have the server run an HTTP Get for all page text, print it (server side) and then pass that text back to the client for printing (client side).
So far I am able to get it to the point where it reads given web page server side and attempts to input that page into a String but for some reason it passes the FIRST line of said string back to the client and nothing else. I also get this error server side:
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(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeBytes(Unknown Source)
at assign1.TCPServer15.main(TCPServer15.java:48)
I am not 100% sure what is going wrong and I have tried to troubleshoot a variety of things, and this is my first time trying to do something like this so I'd love tips!
Here is the code for Client
import java.io.*;
import java.net.*;
class TCPWebClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String webText;
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()));
System.out.print("Enter a single string in the form: server/port. \nExample: (www.google.com/80)\n");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
webText = inFromServer.readLine();
System.out.println("FROM SERVER:\n" + webText);
clientSocket.close();
}
}
And my code for server:
import java.io.*;
import java.net.*;
class TCPServer15
{
public static void main(String argv[]) throws Exception
{
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);
String [] connectionInfo = clientSentence.split("/");
Socket webSocket = new Socket(connectionInfo[0], Integer.parseInt(connectionInfo[1]));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(webSocket.getOutputStream())));
out.println("GET /index.html HTTP/1.0");
out.println();
out.flush();
BufferedReader inFromWeb = new BufferedReader(new InputStreamReader(webSocket.getInputStream()));
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = inFromWeb.readLine()) != null)
{
System.out.println(inputLine);
stringBuilder.append(inputLine);
stringBuilder.append("\n");
}
String finalString = stringBuilder.toString();
inFromWeb.close();
outToClient.writeBytes(finalString);
}
}
}
You are reading only one line in your client. this should be in a while loop (check how you have coded your server while it talks to google. the client should behave the same way.
I have modified your client and server - snippets
Server
outToClient.writeBytes(finalString);
outToClient.flush();
outToClient.close();
inFromWeb.close();
Client
StringBuilder output = new StringBuilder();
while ((webText = inFromServer.readLine()) != null) {
output.append(webText);
output.append("\n");
}
System.out.println("FROM SERVER:\n" + output.toString());
clientSocket.close();
I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.

Basic Java Echo Socket Communication Error

I have been looking through the multitudes of explanation of basic Java Socket use, and have constructed the following basic code for my own Server/Client echo pair. However, there is some hangup in the client code that I cannot find for the life of me. Perhaps someone else can spot it?
// Server Code:
try (ServerSocket serverSocket = new ServerSocket(22222);
Socket cSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(cSocket.getInputStream()))) {
System.out.println("Client connected: " + cSocket.getInetAddress().getHostAddress());
// console DOES print ^this line and correct IP when client is run.
String inLine;
while (true) {
inLine = in.readLine();
out.println(inLine);
if (inLine.equals("exit")) break;
}
// client code
try (Socket socket = new Socket("localhost", 22222);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));) {
String userIn;
while (true) {
System.out.print("Client> ");
userIn = consoleIn.readLine();
out.println(userIn); // code hangs here.
out.flush();
System.out.println("Server> " + in.readLine());
if (userIn.equals("exit")) break;
}
It isn't blocking there. It's blocking in the readLine() from the server. Try a flush() after the println() in the server.

android thread stops with unknown cause

I'm communicating Android Device - PC with TCP Sockets. I sent network packets to the server succesfully but when I try to get response from the server, The thread stops I don't know cause.
Android Client :
public class ClientThread implements Runnable
{
public void run()
{
try
{
Socket socket = new Socket("192.168.1.12", 4444);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(msg);
out.flush();
Log.v("Naber", "One");
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
String inMsg = bufferedReader.readLine();
inputStreamReader.close();
Log.v("Naber", "Two");
socket.close();
}
catch (Exception e)
{
Log.v("Hata", e.getMessage());
}
}
}
Log Verbose Output :
09-25 22:25:37.163 15351-15532/com.mytracia.kumanda9 V/Naberīš• One
I don't know why does it stops when it came to this line :
String inMsg = bufferedReader.readLine();
My Server Application with C#
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 4444);
while (true)
{
tcpListener.Start();
//Program blocks on Accept() until a client connects.
Socket soTcp = tcpListener.AcceptSocket();
Byte[] received = new Byte[1024];
int bytesReceived = soTcp.Receive(received, received.Length, 0);
String dataReceived = System.Text.Encoding.ASCII.GetString(received);
dataReceived = dataReceived.Replace("\0", "");
Console.WriteLine(dataReceived);
String returningString = "Naber1";
Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes(returningString.ToCharArray());
//Returning a confirmation string back to the client.
soTcp.Send(returningByte, returningByte.Length, 0);
tcpListener.Stop();
}
}
Server answer with new line? "\n"
public String readLine () Added in API level 1 Returns the next line
of text available from this reader. A line is represented by zero or
more characters followed by '\n', '\r', "\r\n" or the end of the
reader. The string does not include the newline sequence.
Returns the contents of the line or null if no characters were read
before the end of the reader has been reached.
Try:
String returningString = "Naber1\n";

java client-server issue on client side (no System.out)

probably a noobish Q:
So i made a very simple single-threaded server/client model. Now when i execute the program in the eclipse IDE it shows me System.out's of the server and not the ones from the client.
When i press terminate, the System.out.println lines that were supposed to be generated by Client show up.
I'm struggling with this for days now.. Hopefully someone can help me out.
Thanks in advance!
SERVER:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args)
{
new Server();
}
public Server()
{
try
{
ServerSocket serverSocket = new ServerSocket(8000); //nieuw instantie van een ServerSocket
System.out.println("Waiting for clients..");
Socket socket = serverSocket.accept(); // lister for socket requests
while(true)
{
BufferedReader inputClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(socket.getOutputStream());
String clientInput = inputClient.readLine();
System.out.println("Server: clientInput= : " + clientInput);
InetAddress hostAddress = InetAddress.getByName(clientInput);
String iPaddress = hostAddress.getHostAddress();
System.out.println("Server: IP = : " + iPaddress);
clientOutput.writeBytes(iPaddress);
clientOutput.flush();
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
CLIENT:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
new Client();
}
public Client()
{
try
{
Socket socket = new Socket("localhost", 8000);
DataOutputStream toServer = new DataOutputStream(socket.getOutputStream());
BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer.writeBytes("google.com" + '\n');
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
When you start a client and a server program, they will have 2 separate consoles. Only one is visible at a time in the "Console" view of Eclipse. That is why you only see the server's.
You can switch between the active consoles with the "Display Selected Console" icon (it's a monitor icon) and also see the active console list.
Also you have a full-duplex connection. Both the client and the server can read/write. You use a DataOutputStream - BufferedReader representation for a one-way communication which is WRONG.
DataOutputStream writes binary data, BufferedReader reads text (character) data.
You should use one of the following pairings:
DataOutputStream - DataInputStream and use writeUTF() and readUTF() methods
OR
PrintWriter - BufferedReader and use println() and readLine() methods
clientOutput.writeBytes(iPaddress);
clientOutput.write("\n".getBytes());
clientOutput.flush();
Just add these lines (second line) in your Server class.
Reason
In your Client class you are reading a line from buffer reader but you have not send any character from server indicating end of line. So in the second line we are writing new line character indicating end of line.
When you close the server, connection get reset and available input are read. Thats why your Client prints if you close the server.
Optionally if you only want to modify your Client class you can write these lines
char [] a = new char[100];
int length = fromServer.read(a);
System.out.println("Client: "+(new String(a)).substring(0,length));
Instead of these
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
Ok so after indexing the line with an '\n' and putting the line :
Socket socket = serverSocket.accept();
inside the while loop in stead of inside try{} i got rid of all my problems.
Thanks, now i'll try to multithread this thing!

Categories

Resources