Hello stackoverflow community,
i am stuck at a problem regarding socket communication in Java.
Here is the sample code of my Server and Client class:
Server:
public class OTPServer {
static ServerSocket serverSocket;
final static int PORT = 4242;
static Socket clientConnection;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Socket initialized");
String serverMessage = "Hello, I am the Host";
ServerTool serverTool = new ServerTool();
while (true) {
clientConnection = serverSocket.accept();
if(clientConnection.isConnected()) {
System.out.println("Client connected");
}
BufferedReader clientInputReader = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(clientConnection.getOutputStream());
System.out.println("Sending message to client: " + serverMessage);
serverOutput.writeBytes(serverTool.encodeMessage(serverMessage));
serverOutput.flush();
String clientMessage = clientInputReader.readLine();
System.out.println("Encoded answer from client: " + clientMessage);
String decodedMessage = serverTool.decodeMessage(clientMessage);
System.out.println("Decoded answer from client: " + decodedMessage);
serverOutput.close();
clientInputReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Hello, I am the OTP Server!");
}
Here is the Client:
public class OTPClient {
static Socket clientSocket;
final static int PORT = 4242;
final static String HOST = "localhost";
public static void main(String[] args) {
System.out.println("I am the OTP Client!");
String serverMessage;
String clientResponse = "I am the Client";
OTPTool otpTool = new OTPTool();
try {
clientSocket = new Socket(HOST, PORT);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Connection to Host established");
serverMessage = serverInput.readLine();
System.out.println("Encoded Message from Server: " + serverMessage);
String decodedMessage = otpTool.decodeMessage(serverMessage);
System.out.println("Decoded message from Server: " + decodedMessage);
System.out.println("Answering with own message: " + clientResponse);
outputStream.writeBytes(clientResponse);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Now where is my problem:
The connection establishes and the Server seems to send its message to the client and waits for a answer. The Client does not print the message he got from the Server.
As soon as i cancel the Server the client prints the message it gets from the server as well as the information, that the answer is send end exits with exit code 0 so it seems that this part is fine it just is stuck somehow.
I already tried to flush the outputStream as you see in the example code given.
Is there something obvious im missing?
I know, this is really basic stuff but its my first time using sockets for communication.
Thank you in advance!
Best Regards,
Ronny
Btw: i know that the server only connects to one client requesting a connection. Thats absolutely sufficient for my use.
It is getting stuck because serverInput.readLine(); blocks until either a line break or end of file is encountered. On the server side, you are not sending a line break, so the client blocks.
Related
I have read through most similar questions in Stack-overflow . But i can't find similar one.
I build one client and one server. For my client networking, i build a class which contains a socket and many relevant methods like this :
public class Connector {
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
public Connector(int x) throws UnknownHostException, IOException{
socket=new Socket("localhost",x);
}
public boolean isConnected(){
return socket.isConnected();
}
public void sendInfo(String str) throws IOException{
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
}
public String receiveInfo() throws IOException{
input = new DataInputStream(socket.getInputStream());
return input.readUTF();
}
public boolean loginSuccess() throws IOException{
input = new DataInputStream(socket.getInputStream());
return input.readBoolean();
}
}
and when my client runs(the server run in my IDE),
String userAccount = "VerifyAccount" + "#" + userNametf.getText() + "#" + passwordtf.getText() + "#" + i;
connector.sendInfo(userAccount);
if(connector.isConnected())
System.out.println("the connector is still connected!");
else
System.out.println("the connector is no connected!");
if(connector.loginSuccess()){
System.out.println("Log in success");
}
else;
and this is my server:
ServerSocket serverSocket = new ServerSocket(8000);
while(true){
Socket socket = serverSocket.accept();
Thread thread = new Thread(()->{
try{
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
String tempStr = input.readUTF();
System.out.println("Server receive data : "+tempStr);
String[] tempStrArray = tempStr.split("#");
if(tempStrArray[0].equals("VerifyAccount")){
if(UserVerification.isValid(tempStr.substring(14))==1){
output.writeBoolean(true);
output.flush();
}
else{}
}
else if(tempStrArray[0].equals("RegisterAccount")){}
else{}
}
catch(IOException ex){
ex.printStackTrace();
}
});
thread.start();
}
So the whole process is that the client socket connects to the server socket ,
then client send one string to the server , the server process the string , and write a boolean value back to the client , but when i call connector.LoginSuccess() , the compiler will throw an exception like this:enter image description here
You are never closing the accepted socket. You are also attempting to read a boolean that may never be sent. And, as I said in comments, isConnected() doesn't do what you think it does: it doesn't magically start returning false when the peer disconnects.
I have a socket programming code that goes..
Server Program
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(50000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
And the client side code that is...
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
The code compiles fine. But when i run the program, first the server and then the client, the server displays that
Waiting for client on port 9000...
Socket timed out!
and the client shows
Connecting to MyServerName on port 9000
What is wrong with the code?? I have tried increasing and decreasing the timeout values but it gives the same output.
What is wrong with the code?
There's nothing wrong with your code. You set a 50 second accept timeout, accept blocked for 50 seconds without a client trying to connect, so a SocketTimeoutException was thrown. Everything here is working as designed.
Of course it's possible that:
your accept timeout is too short
you don't want to abort your server just because of an accept timeout
you don't want an accept timeout at all.
All of these are design decisions that depend on your requirements.
It's also possible that you got the host name wrong in the client, but as you're ignoring exceptions in the client:
catch(IOException e)
{
}
there is no way you will ever find out. Never ignore IOExceptions.
Above code is perfectly working with sName in client as 'localhost', since I am running both client and server in my local:
String sName = "localhost";
Verify your server-name if you are expecting client to connect to server.
I'm trying to program a Server Client program where the CLIENT will be prompt if the SERVER closes or loses connection. What happens is once I connect the server and the client then disconnects the server it doesn't go to the ConnectException part
example: I opened the Server and Client connects, in the Client it will show that "You are connected to the Server", then if the Server disconnects there should be a "Server is disconnected". and when the Server reopens it will prompt the Client that he's connected to the Server
How can I continuously check if the Server is open or disconnected
here's my code:
SERVER
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
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.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
CLIENT
public class Client
{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
System.out.println("Connected to the Server");
}
catch (ConnectException exception)
{
System.out.println("Server is still offline");
}
catch(IOException ex)
{
System.out.println("Server got disconnected");
}
}
}
Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.
So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.
The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.
That way you can keep track of up time and down time.
you can do like this
try
{
Socket s = new Socket("address",port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
DataInputStream is = new DataInputStream(s.getInputStream());
while (true)
{
os.writeBytes("GET /index.html HTTP/1.0\n\n");
is.available();
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("connection probably lost");
e.printStackTrace();
}
or you can simply et connection time out like this socket.setSoTimeout(timeout); to check connectivity
or you can use
socket.getInputStream().read()
makes the thread wait for input as long as the server is connected and therefore makes your program not do anything - except if you get some input and
returns -1 if the client disconnected
or what you can do is structure your code in this way
while(isConnected())
{
// do stuffs here
}
been trying to figure this problem out for about 5 hours but cant seem to see it, although all the steps are done to send data, I can only receive messages to the server, but not from server to client. I'm in the early stages of building/learning how to do a chat client program in command line. The following is the server code:
The CServer class:
public class CServer {
private static int port=2008, maxConnections=0;
private static String shutDownServer = "no";
public static void main(String[] args) throws IOException{
ServerSocket listen = new ServerSocket(port);
Socket server;
while(shutDownServer.equalsIgnoreCase("no")){
doComm connection;
System.out.println("\nWaiting for clients to connect...");
server = listen.accept(); // accept incomming connections from client
System.out.println("Client connected. Location: " + server.getInetAddress().getHostName());
connection = new doComm(server);
Thread thread = new Thread(connection);
thread.start();
}
}
public void shutDownServer(String command){
this.shutDownServer = command;
}
}
Now the doComm class that handles each client in thread:
public class doComm implements Runnable{
Socket server;
private String clientData;
public doComm(Socket server){
this.server = server;
}
public void run(){
try {
BufferedReader fromClient = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream toClient = new DataOutputStream(server.getOutputStream());
clientData = fromClient.readLine();
System.out.println("Client sent: "+clientData);
(( The problem -imo- may be either this statement: ))
toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");
//server.close();
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e);
e.printStackTrace();
}
}
}
Now the client class CClient:
public class CClient {
static String address = "localhost";
static int port = 4444;
static Socket echoSocket;
public CClient(int port, String addr){
changePort(port);
changeAddr(addr);
}
public static void main(String[] args) throws IOException, UnknownHostException{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the port to connect to: ");
int temp_port = Integer.parseInt(scan.nextLine());
System.out.println("Please enter the address of server: ");
System.out.flush();
String temp_addr = scan.nextLine();
CClient client = new CClient(temp_port,temp_addr);
PrintWriter out = null;
BufferedReader in = null;
try{
System.out.flush();
echoSocket = new Socket(address,port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}
catch(IOException e){
System.err.println("IOException error: " + e.getStackTrace());
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("thingy prints right after this...");
(( or here: ))
System.out.println("echo: " + in.readLine());
}
}
public void changePort(int port){
this.port=port;
}
public void changeAddr(String addr){
this.address=addr;
}
}
clientData = fromClient.readLine();
toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");
This is a very common problem whose root cause is the failure to document and specify the protocol being used for communication. Here you are receiving lines but sending bytes. If you had a protocol document, it would either specify that lines were exchanged or that arbitrary units of bytes were exchanged. That would show that one of these lines of code is wrong, and you could fix it. But without a protocol specification, you can't even tell which side is wrong.
Please, take my advice from years of painful lessons -- document a protocol before you implement. Then, if it doesn't work, you can follow this three step process:
Does the client follow the documented protocol? If not, it is broken.
Does the server follow the documented protocol? If not, it is broken.
The protocol specification is broken.
In this case, the protocol specification would document what constitutes a "message" for your protocol. It would then be each side's responsibility to send complete messages and find these message boundaries on receive. However, in your case, one piece of code expects a line terminator to mark a message boundary and the other side doesn't send one.
Is the sender wrong to omit a message boundary? Is the receiver wrong to insist on receiving one? Nobody knows because there's no specification to say what's the right thing to do.
I am trying to write server to client program but I cannot communicate with the server in Java.
Here is the code block in my main.
InetAddress addr = InetAddress.getLocalHost();
ipAddress = "78.162.206.164";
ServerSocket serverSocket = new ServerSocket(0);
String randomStringForPlayerName = RandomStringGenerator.generateRandomString();
baseForReqOpp += ipAddress + " " + serverSocket + " " + randomStringForPlayerName;
Socket socket = new Socket(host,2050);
socket.setSoTimeout(100);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
out.write(baseForReqOpp);
out.flush();
System.out.println(in.read());
I know that there is no problem in the server code and all the communication ports are ok.
But I cannot read anything from the server.
What can be the problem?
you have to create an output stream before the input stream
Here is some working code with communicating client and server sockets. Hopefully you can adapt it for your specific problem.
public class SocketTest {
public void runTest() {
try {
// create the server
new SimpleServer().start();
// connect and send a message
InetAddress addr = InetAddress.getLocalHost();
Socket sock = new Socket(addr, 9090);
ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
out.writeObject("Hello server");
out.flush();
ObjectInputStream in = new ObjectInputStream(sock.getInputStream());
System.out.println("from server: " + in.readObject());
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// server has to run in a separate thread so the code doesn't block
private class SimpleServer extends Thread {
#Override
public void run() {
try {
ServerSocket sock = new ServerSocket(9090);
Socket conn = sock.accept();
// the code blocks here until a client connects to the server
ObjectInputStream in = new ObjectInputStream(conn.getInputStream());
System.out.println("from client: " + in.readObject());
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.writeObject("Hello client");
out.flush();
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
To run it:
new SocketTest().runTest();
Your code will never work because you don't use threads. In order to start the server, you need to call accept at some point in your code
myServerSocket.accept();
this is a blocking call, ie the code flow stops until a client connects. But since you can't execute any statement (remember accept is blocking?) how can a client connect? This chicken and egg problem is resolved through threads. See Howard's answer for a code sample.
I don't see any call to accept(), so I wonder what your client connects to...