This is a problem I never figured out. I've asked many people, and they don't even know. Anyways, lets get to the problem. Here's what I tried to do... Create a client and a server. The client connects to the server, and sends a message to it every 3 minutes (I reduced the time for testing). There has to be two independent threads however (one for the client and server). What I found was, the client would continue to send messages, but the server would no longer listen on port 1234.
Client:
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public Client(){
startClient();
}
public void startClient(){
new Thread(new Runnable(){
#Override
public synchronized void run(){
try{
Socket sendChat = new Socket("localhost", 1234);
PrintWriter writer = new PrintWriter(sendChat.getOutputStream());
while(true){
Thread.sleep(1000); // normally 180000
writer.println("Hello Server!");
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Server:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public Server(){
startServer();
}
public void startServer(){
new Thread(new Runnable(){
#Override
public synchronized void run(){
try{
#SuppressWarnings("resource")
ServerSocket server = new ServerSocket(1234);
while(true){
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
while(!test.isClosed()) {
Date date = new Date();
System.out.println("Server got message from client " + date);
}
reader.close();
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Start:
public class Start {
public static void main(String[] args){
new Server();
new Client();
}
}
I would greatly appreciate it if someone could tell me what is wrong, because I honestly have no clue.
Write below two lines out of while loop in Server class and it will work for you.
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
What is happening in your code : Server will wait for new client every time after completion of the while loop but there is no client which is going to connected with server at that instance. So server will wait untill a new client will come and server will accept that new client and continue its processing.
you are stack in a loop, try close the connection in the client after the message.
See these links they use
socket.setKeepAlive(true);
java.net.Socket TCP keep-alive usage
and
Permanent and persistent Socket connection in java
Related
I am complete beginner and i have assignment to send something to server and get it back while using threads too.
My problem is that no matter which port I use, I get connection refused.
I think it might something to do with threads, but I am unsure what to do with them as it seems both start properly and client is the one throwing exception. I read somewhere that server should have some time to start connection so I put sleep but same thing again.
Main:
package advancedjavaassignment1;
public class MAIN {
public static void main(String[] args) {
SERVER.mainServer();
CLIENT.mainClient();
}
}
SERVER:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class SERVER {
static void mainServer() {
serverTHREAD serverThread = new serverTHREAD();
serverThread.start();
try (
ServerSocket calcServer = new ServerSocket(10001); //Server created on port 2390
Socket inSocket = calcServer.accept(); //Server is listening
DataInputStream FromClient = new DataInputStream(inSocket.getInputStream());
DataOutputStream ToClient = new DataOutputStream(inSocket.getOutputStream());) {
int a = FromClient.readInt();
ToClient.writeInt(a);
}
catch (IOException e) {
System.out.println(e.getMessage()+ "Server");
}
}
}
}
CLIENT:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class CLIENT {
static void mainClient() {
serverTHREAD clientThread = new serverTHREAD();
clientThread.start();
try {Thread.sleep(2000); System.out.println("break");} catch (InterruptedException ex) { }
try (Socket ClientSocket = new Socket("localhost",80);
DataInputStream FromServer = new DataInputStream(ClientSocket.getInputStream());
DataOutputStream ToServer = new DataOutputStream(ClientSocket.getOutputStream());) {
ToServer.writeInt(10);
int sum = FromServer.readInt();
System.out.println(sum);
ClientSocket.close();
}
catch(IOException exception)
{
System.out.println(exception.getMessage() + " - Client");
}
}
}
Looks like your server runs on port 10001 (although you wrote 2390 in the comment) and the client tries to connect to port 80. The client finds no server listening on that port, hence the connection refused error.
My apology, I forgot to change it, as I was experimenting with everything, this does not work even when ports are same.
I solved this by implementing Runnable. Worked immediately.
I'm trying to realize a simple client/server application in Java8.
I'm using this code:
`package prova;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String args[]){
ServerSocket ssock;
try {
System.out.println("Listening");
ssock = new ServerSocket(8080);
while(true){
Socket sock;
try {
sock = ssock.accept();
System.out.println("Connected");
new Thread(new Server(sock)).start();
}catch(IOException e1){e1.printStackTrace();}
}
}catch(IOException e2){e2.printStackTrace();}
}
}`
Server.java
package prova;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public class Server implements Runnable{
Socket clientSocket;
public Server(Socket cSocket){
this.clientSocket = cSocket;
}
public void run(){
try {
PrintStream pstream = new PrintStream
(clientSocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i +
" bottles of beer on the wall");
}
pstream.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
When the application arrives to execute the instruction ssock.accept();
the application crashes. I really don't know what's the matter with this code. I've searched on internet but except for class server there is no difference between my code and a lot of solution/examples that i found. By the way since the application doesn't arrive to execute the thread I guess this is not related to my issue, maybe I'm wrong.
Thank you all in advance
that's the strange fact it doesn't provide any stacktrace. I'm running this code on win10 with eclipse mars 4.5.2. the code stops at this instruction sock = ssock.accept();
Yes, it's supposed to stop there -- it's waiting for a client program to connect on that same socket, server socket 8080, that's what accept() does, but you don't do that anywhere. The fix is simple -- have your client try to connect on the same socket that the server is waiting on.
I wanted to send a string of text from my android phone over to a Java server running on my PC and it works but only once, it would receive the first string but when I type in another one on my phone and I press the button, the server doesn't receive anything, (here is my code for the android app):
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messsage = etMsg.getText().toString();
etMsg.setText("");
new Thread(new Runnable() {
#Override
public void run() {
try
{
client = new Socket(etIP.getText().toString(), port);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
});
And here is the code for the Java server:
package src;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class VRS {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(4444);
System.out.println("server started on port 4444");
clientSocket = serverSocket.accept();
}catch(Exception e){} //read & display the message
//BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Scanner in1 = new Scanner(clientSocket.getInputStream());
String mes;
while(true){
if (in1.hasNext())
{
mes=in1.nextLine();
System.out.println("Client message :"+mes + System.lineSeparator());
}
}
}
}
Can anyone help me find the problem as I'm a beginner in terms of Java.
The scanner on the server is waiting for a complete token with a terminator and you are not sending one from the client. Try appending a line terminating character on the client side e.g.
printwriter.println(messsage);
In addition to that it seems that for every click on the client side a new Socket object is created. But the server is not waiting for a new connection. You can either :
reuse the Socket on the client side instead of creating a new one for every click. e.g. make your client variable a class member.
On the server side after each message call clientSocket = serverSocket.accept(); again to create a new Socket. This new server side Socket will correspond to the new Socket on the client.
The first option is considered more efficient especially as the number of connections and messages you want to handle increases.
I recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.
This is the client code:
import java.io.*;
import java.net.*;
class ServerTest{
public static void main(String args[]) throws Exception{
Socket clientSocket = new Socket(myIpAdress, 8001);
//Send the message to the server
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sendMessage = "randSubstring:StackOverflowIsAwsome";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent: "+sendMessage);
String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
System.out.println("Message received from the server : " +message);
clientSocket.close();
}
}
My server code consists of two classes. This one is the listener:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket socket = new ServerSocket(8001);
while(true) {
Socket connectionSocket = socket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = input.readLine();
if(clientSentence.startsWith("randSubstring:")){
Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
connection.start();
}
Thread.sleep(300);
}
}
}
This is the thread that will not start until the client is stopped:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
public class ServerConnection implements Runnable{
private Socket serverConnection;
private String sentence;
public ServerConnection(Socket connection, String clientSentence){
serverConnection = connection;
sentence = clientSentence;
}
#Override
public void run() {
Random r = new Random();
String substring = sentence.substring(0, r.nextInt(sentence.length()));
try {
OutputStream os = serverConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(substring);
bw.close();
out.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.
In the server you do a readLine(..), which means that it will wait for a end-of-line character.
But in your sender code, you just send a string with no line ending.
So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"
You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.
NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.
I'm trying to code a server-client communicating application which uses two separate threads, one for input and one for output. I'm having a weird "deadlock" issue, though: when one thread reads input, but the client hasn't sent anything, the thread stops (since it's waiting for input). However, for some reason, while the input thread is blocked, the output thread can't write anything.
This is illustrated in this code sample:
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class TestServer {
public static void main(String... args) throws IOException {
/* Creates a server socket that lurks about our port waiting for connections */
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(4114));
while(true){
SocketChannel connectionChannel = serverChannel.accept();
if(connectionChannel != null){
final Socket connection = connectionChannel.socket();
new Thread(){
public void run(){
try {
System.out.println("READING");
System.out.flush();
// If the next line is commented out, nothing blocks
connection.getInputStream().read();
System.out.println("DONE READING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
System.out.println("WRITING");
System.out.flush();
new DataOutputStream(connection.getOutputStream()).writeBytes("AUGH!!!");
//connection.getOutputStream().write(5);
System.out.println("DONE WRITING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
break;
}
}
}
}
And the client code:
import java.net.*;
import java.io.*;
public class TestClient {
public static void main(String... args) throws IOException {
Socket connection = new Socket("127.0.0.1", 4114);
while(true){
System.out.println(connection.getInputStream().read());
}
}
}
The code sample above blocks, but if the line in the server is commented out it doesn't. Why is that? Is a socket limited to only waiting for input/output at the same time? What's going on?
I'm not sure why you are seeing this, but it has something to do with using channels.
If you replace this code with
ServerSocket ss = new ServerSocket(4114);
Socket connection = ss.accept();
it will work as you want.