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.
Related
I tried to connect two machines using Socket.
I put client code in Machine A:
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("IP ADDRESS",5555);
// Socket s = new Socket("localhost",6669);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Run the server code in Machine B
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept(); //establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Both in machine in same network
But its not running and no error also coming in CMD.
First of all, when I compile the code using "localhost" as the hostname, and run the client and server apps on the same machine ... it works. The server receives the message and prints it.
From this, I conclude that the code is correct (enough) and the real problem is something to do with your networking; e.g.
It might be a routing problem.
It might be a firewall problem.
There might be something wrong with your physical network or network interfaces.
However none of these are programming problems.
my name is Jędrzej and I am new here. I was trying to write a simple chat in java. I am trying to make multithread server so multiple clients can connect to this server. My client works fine, but if I run two clients, they dont see each others responses. Code bellow:`
package serverthread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerWIthThreads {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1234);
while(true){
Socket socket = serverSocket.accept();
Runnable r = new ThreadForServer(socket);
Thread t = new Thread(r);
t.start();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
package serverthread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ThreadForServer implements Runnable{
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ThreadForServer(Socket i){
socket = i;
}
#Override
public void run(){
try{
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
while(true){
String message = (String) inputStream.readObject();
outputStream.writeObject(message);
outputStream.flush();
}
}catch(IOException e){
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`
The way you've implemented this, you're reading a message from one client and then writing it back to the same client.
You'll need to revise your program so that you can write the message to the Socket of the other connected client.
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 tried to find something similar to help me with my code and I also tried to do it by myself but I got stuck on the end and I would really appreciate if someone would help me with that.
So I have already working simple Java Client/Server code and what i want to do is to upgrade it so it can work both ways, right now after launching the server and connecting to it by the client everything what u write as a client will be shown on the server too and i want to upgrade it so what i write on the client will be shown on the server and what i write on the server will be shown on the client.
myServer.java
import java.io.*;
import java.net.*;
public class myServer {
public static void main (String[] args) {
try {
int i=0;
ServerSocket ss = new ServerSocket(9000);
System.out.println("Listening...");
Socket s = ss.accept();
System.out.println("Connection accepted");
InputStream d1 = s.getInputStream();
while ((char)i !='q')
{
i = d1.read();
System.out.print((char)i);
}
s.close();
ss.close();
} catch (Exception e) {System.out.println("Error"); }
}
}
myClient.java
import java.io.*;
import java.net.*;
public class myClient {
public static void main(String[] args) {
try {
int i=0;
Socket s=new Socket("localhost",9000);
OutputStream o = s.getOutputStream();
while ((char)i !='q')
{
i = System.in.read();
o.write((char)i);
}
s.close();
} catch(Exception e) {System.out.println("Error"); }
}
}
Thank You in advance.
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