java.net.ConnectException: Connection refused TCP - java

Objective - I want to send the entered text in the java (PC) project to the android app which displays this text.The PC is connected to wifi
hotspot created by the android mobile.
The PC/client java project code:
public class EcsDemo {
public static void main(String[] args) {
System.out.println("Enter SSID to connect :");
Scanner in = new Scanner(System.in);
String ssid = in.nextLine();
System.out.println("You entered ssid " + ssid);
System.out.println("Connecting to ssid ..");
DosCommand.runCmd(DosCommand.connectToProfile(ssid));
// netsh wlan connect name=
System.out.println("initializing tcp client ..");
try {
TCPClient.startTCpClient();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TCPClient {
public static void startTCpClient() throws UnknownHostException, IOException{
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
Android app/Server code:
public class MainActivity extends Activity {
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "starting server");
new ServerAsyncTask().execute();
}
}
public class ServerAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
TCPServer.startTCPServer();// initTCPserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static void startTCPServer() throws IOException{
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
Log.i("startTCPServer","TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
Log.i("startTCPServer"," THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
// System.out.println("SEND(Type Q or q to Quit):");
// toclient = inFromUser.readLine();
//
// if (toclient.equals("q") || toclient.equals("Q")) {
// outToClient.println(toclient);
// connected.close();
// break;
// } else {
// outToClient.println(toclient);
// }
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
After running the android app and then when I run the java project I get the following exception:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.expressecs.javademo.TCPClient.startTCpClient(TCPClient.java:15)
at com.expressecs.javademo.EcsDemo.main(EcsDemo.java:41)
I have referred to the following links:
java.net.ConnectException: Connection refused
Thanks!

There is nothing listening at the IP:port you are trying to connect to.
Your server didn't start, or is listening to a different port, or is bound to 127.0.0.1 instead of 0.0.0.0 or a public IP address.

Related

Java socket sends only one message

I have made a socket in Java.
This socket connects with a server.
When I start my program, the server sends a message that my socket is connected with the AEOS.
When I try to login to the server for sending some commands, then the server responds again with: status connected to AEOS version
This is not the message that I expect, normally my server must send a "response true".
Can you help me?
Thanks.
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
while(true) {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
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);
clientSocket.close();
}
}
}
output socket
Why don't you try to read everything that server had sent? Also, need to open a new Socket every-time? Depends on your implementation. Try this:
public static void main(String[] args) {
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String initialMessageFromServer = null;
while ((initialMessageFromServer = inFromServer
.readLine()) != null) {
System.out.println(initialMessageFromServer);
}
while (true) {
String sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
StringBuilder modifiedSentence = new StringBuilder();
String responseFromServer = null;
while ((responseFromServer = inFromServer.readLine()) != null) {
modifiedSentence.append(responseFromServer);
modifiedSentence.append('\n');
}
System.out
.println("FROM SERVER: " + modifiedSentence.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Java - connection always resets when sending data from client to server

I don't know what's wrong with the code as it always resets the connection when I send an input from Client to Server. The error report indicates problem on get.readLine() on Client code.
This is the code on Client Side:
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class Client
{
public static void main(String[] args) throws UnknownHostException, IOException
{
String hostName = "localhost";
Socket client = null;
try{
client = new Socket(hostName, 9972);
}catch(UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
PrintWriter send = new PrintWriter(client.getOutputStream(), true);
BufferedReader get = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a 7-bits binary to send: ");
String input;
while((input = read.readLine()) != null)
{
String codeWord = addParity(input);
send.println(codeWord);
System.out.println("Server responds: " + get.readLine());
}
send.close();
get.close();
read.close();
client.close();
}
public static String addParity(String data)
{
//Some code block here
}
}
This is the code on Server Side:
import java.io.*;
import java.net.*;
import java.util.Random;
import java.util.ArrayList;
public class Server
{
public static void main(String[] args) throws IOException
{
int port = 9972;
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
PrintWriter send = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader get = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input;
while((input = get.readLine()) != null)
{
if(input.length() == 11 && input.matches("[01]+"))
{
String data = "";
Random rand = new Random();
int change = rand.nextInt(1);
for(int I = 0; I < change; i++)
{
data = modify(input);
}
String result = HammingCheck(data);
send.println(result);
}
else
send.println("Input is invalid. Echo: " + input);
if(input.equals("bye"))
break;
}
send.close();
get.close();
clientSocket.close();
serverSocket.close();
}
public static String modify(String input)
{
//Some code to modify the string
}
public static String HammingCheck(String data)
{
//Some code to perform hamming code checking
}
public static String removeParity(String data)
{
//some code to remove parity bits
}
}
This is the error report:
Attempting to connect to server at host: localhost
Connection established.
Enter a 7-bits binary string as message to server: 1111111
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at ClientSide.Client.main(Client.java:35)

Chat server client sometimes cannot see message from other clients on the same server

I am making 2 classes for Chat server client for a project I am working on. The problem is server can see the message that sent to it(from client) and it can send those messages out to every clients BUT each client has to type in some input first if he wants to see the message from other users. I have no clue what I did wrong. Please help me out. Thanks in advance :)
Server Class
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class TestServer extends Thread
{
protected Socket clientSocket;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
final static int PORT = 22;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
System.out.println ("Connection Socket Created");
try
{
while (true)
{
System.out.println ("Waiting for Connection");
Socket sock = serverSocket.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
new TestServer (sock);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private TestServer (Socket inSock)
{
clientSocket = inSock;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
//System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while (true)
{
inputLine = in.readLine();
System.out.println ("Server: " + inputLine);
for(int i = 1; i <= TestServer.ConnectionArray.size(); i++)
{
System.out.println("Total Connection: " + ConnectionArray.size());
Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i-1);
if (clientSocket != TEMP_SOCK)
{
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
TEMP_OUT.println(inputLine);
TEMP_OUT.flush();
System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
}
}
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client Class
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname);
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 22);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("Other user: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need a separate thread in the client for reading from the server without blocking on System.in;
Thread t = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Other user: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
}
t.interrupt();

Java server client (I/O connectionException)

I have written a program where the client should be able to establish connection, and write to som message to the server. And the server should print this message.
The problem is that once the client connect to the server, I get an exception with the following message:
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at Client.<init>(Client.java:21)
at Server.startServer(Server.java:42)
at Server.main(Server.java:62)
My code for the server is as shown below:
import java.io.*;
import java.net.*;
public class Server {
private int port = 5555;
public void printServerAddress() {
InetAddress i = null;
String host = null;
try {
i = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
host = i.getHostAddress();
System.out.println("Contact this server at address: " + host + " and port: " + port);
}
public void startServer() {
ServerSocket serverSocket = null;
BufferedReader reader = null;
Socket socket = null;
String fromClient = null;
try {
serverSocket = new ServerSocket(port);
while(true) {
socket = serverSocket.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(socket != null) {
System.out.println("Connection from: " + socket);
}
Thread thread = new Thread(new Client(socket));
thread.start();
while((fromClient = reader.readLine()) != null) {
System.out.println("From client: " + fromClient);
}
reader.close();
socket.close();
}
} catch (IOException e) {
}
}
public static void main(String[] args) {
Server server = new Server();
server.printServerAddress();
server.startServer();
}
}
And the code for the client is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client implements Runnable{
private int port;
private String serverAddress;
private PrintWriter writer;
private BufferedReader reader;
public Client(Socket socket)
{
try {
socket = new Socket(serverAddress, port);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
System.out.println("Write message to server:");
Scanner scanner = new Scanner(System.in);
while(scanner.next() != "quit") {
writeToServer(scanner.next());
}
writer.close();
}
public void writeToServer(String message) {
writer.write(message);
}
public void readFromServer() {
String msg = null;
try {
while((msg = reader.readLine()) != null) {
System.out.println("From server: " + msg);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
new Client(s);
}
}
Any idea on what I did wrong, and how to fix my problem?
socket = new Socket(serverAddress, port);
serverAddress is null and port is 0.
try to define the serverAddress variable and the port before call new Socket(serverAddress, port)
or change
socket = new Socket(serverAddress, port);
to
this.socket = socket;
edit
you can change your constructer to :
public Client(String serverAddress, int port)
{
try {
Socket socket = new Socket(serverAddress, port);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

java telnet socket client

Hi guys i've written a simple telnet socket client in java and i'm trying to connect to the telnet services on localhost within windows 7 Pro. The code is executing fine but it is failing to printout out the the output stream and input stream instead the code trow the following exception:
Attemping to connect to host localhost on port 1024
Couldn't get I/O for the connection to: localhost
Is there something that i'm missing ??? THE CODE IS BELOW
Thanks in advance.
import java.io.*;
import java.net.*;
import java.util.*;
public class telnetClients {
public static void main(String[] args) throws IOException {
String telnetServer = new String ("localhost");
int port = 1024;
if (args.length > 0)
telnetServer = args[0];
System.out.println ("Attemping to connect to host " +
telnetServer + " on port "
+ port);
Socket ClientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
ClientSocket = new Socket(telnetServer, port);
ClientSocket.setSoTimeout(20000);
// PrintStream com = new PrintStream(ClientSocket.getOutputStream());
// System.out.println(com);
// BufferedReader inCom = new BufferedReader(new InputStreamReader (ClientSocket.getInputStream()));
out = new PrintWriter(ClientSocket.getOutputStream(), true);
System.out.println(out);
in = new BufferedReader(new InputStreamReader(
ClientSocket.getInputStream()));
String command = in.readLine();
if(in != null);
System.out.println(in);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + telnetServer);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + telnetServer);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"bye\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("bye"))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
ClientSocket.close();
}
}
sample for you which worked for me
public static void main(String[] args) {
String url = "hostname";
int port = 8080;
try (Socket pingSocket = new Socket(url, port)) {
try (PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));) {
out.println("ping");
System.out.println("Telnet Success: " + in.readLine());
}
} catch (IOException e) {
System.out.println("Telnet Fail: " + e.getMessage());
}
}
I think that your problem is probably that the Telnet service is not enabled. In Windows 7 you can check this in Programs and Features (Control Panel) under Windows features.
After that you have to configure the port because the default port por a TCP connection is 23. You can do this with tlntadmn [\\server] config port=PortNumber

Categories

Resources