ConnectException thrown using ServerSocket - java

The following code is correct when compiled, but when run it says: ConnectException
the error image:
import java.net.*;
import java.io.*;
class TcpChat
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("Ip",20000);
ServerSocket ss = new ServerSocket(20000);
new Thread(new TcpClient(s)).start();
new Thread(new TcpServer(ss)).start();
}
}
class TcpClient implements Runnable
{
Socket s;
TcpClient(Socket s)
{
this.s = s;
}
public void run()
{
try
{
OutputStream out = s.getOutputStream();
out.write("hello javaserver".getBytes());
s.close();
}
catch (Exception e)
{
}
}
}
class TcpServer implements Runnable
{
ServerSocket ss;
TcpServer(ServerSocket ss)
{
this.ss = ss;
}
public void run()
{
try
{
Socket s = ss.accept();
InputStream in = s.getInputStream();
byte[] buf =new byte[1024];
int length =in.read(buf);
String ip =s.getInetAddress().getHostAddress();
String data = new String(buf,0,length);
System.out.println(ip+":::"+data);
s.close();
ss.close();
}
catch (Exception e)
{
}
}
}
Additionally, there is no error about the IP address I use, in my PC I use my own IP.

You didn't post your whole code, so it's hard to check, but it seems like you try to connect to a port (i.e. open the client socket) before you actually open the server socket. That won't work, of course, since there's nothing listening at that port yet (thus: connection refused).

Change your main method like
ServerSocket ss = new ServerSocket(20000);
Socket s = new Socket("127.0.0.1", 20000);
new Thread(new TcpServer(ss)).start();
new Thread(new TcpClient(s)).start();
You can find a better example for Chat Server here. Also you can read about sockets from here

Related

java.net.ConnectException: Connection refused: connect occured

I am trying to run the code in a windows comman line and received exception :
D:\dasi\java\javaLab>java ServerClient
java.net.ConnectException: Connection refused: connect
java.lang.StringIndexOutOfBoundsException: String index out of range: -2
D:\dasi\java\javaLab>
in another command line windw :
D:\dasi\java\javaLab>java SocketClient
java.net.ConnectException: Connection timed out: connect
D:\dasi\java\javaLab>
Server code :
import java.io.*;
import java.net.*;
public class ServerClient {
public ServerClient(int port) {
Server server = new Server(port);
server.start();
Client client = new Client(port);
client.start();
}
public static void main(String[] args) {
ServerClient s1 = new ServerClient(7777);
}
}
class Server extends Thread {
int port;
ServerSocket server;
Socket socket;
DataOutputStream outStream = null;
DataInputStream inStream = null;
public Server(int poort) {
try {
this.port = port;
server = new ServerSocket(port);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public void run() {
try {
socket = server.accept();
outStream = new DataOutputStream(socket.getOutputStream());
inStream = new DataInputStream(socket.getInputStream());
System.out.println("server is ok, please continue!");
while(true) {
String str = inStream.readUTF();
System.out.println("The server receive String:"+str);
outStream.writeUTF(str);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
class Client extends Thread {
int port;
Socket socket;
DataInputStream inStream = null;
DataOutputStream outStream = null;
public Client(int port) {
try {
this.port = port;
socket = new Socket(InetAddress.getLocalHost(),port);
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
System.out.println("client is ok, please continue!");
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public void run() {
try {
while(true) {
byte[] b = new byte[1024];
String str = "";
int m = System.in.read(b);
str = new String(b,0,0,m-1);
outStream.writeUTF(str);
str = inStream.readUTF();
System.out.println("The client receive String:"+str);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
Client code :
import java.net.*;
import java.io.*;
public class SocketClient {
Socket s = null;
DataInputStream inStream = null;
DataOutputStream outStream = null;
public SocketClient() {
try {
init();
waitData();
}
catch(Exception e) {
System.out.println(e.toString());
}
}
void init() throws Exception {
s=new Socket("10.15.43.216",8765);
inStream = new DataInputStream(s.getInputStream());
outStream = new DataOutputStream(s.getOutputStream());
s.setSoTimeout(3000);
}
void waitData() {
while(true) {
try {
String str = inStream.readUTF();
System.out.println("Client accept:" +str);
str = Integer.toString(Integer.parseInt(str)+1);
outStream.writeUTF(str);
}
catch(Exception e) {
System.out.println(e.toString());
break;
}
}
}
public static void main(String[] args) {
new SocketClient();
}
}
I am wodering if there's anything wrong in my code or if it was my computer port that cause the problem. Because when I checked my computer port I didn't see 7777. When I issued command netstat -nao | findstr 7777, it returned nothing.
D:\dasi\java\javaLab>netstat -nao | findstr 7777
D:\dasi\java\javaLab>
If it was the port problem, then how to open the 7777 port.
I am a newbie here, please help. Thanks a lot!
replace
public Server(int poort) {
try {
this.port = port;
...
}
}
with
public Server(int poort) {
try {
this.port = port;
...
}
}
or rather the default value of port is zero, then your serverSocket will bind with 0 port rather than 7777.
and as for this code segment:
public ServerClient(int port) {
Server server = new Server(port);
server.start();
Client client = new Client(port);
client.start();
}
I am afraid it is easy to make you in trouble, because we cant ensure the server thread will execute before client thread and if client thread execute first when server havent run it will cause error. And you already have a client in another java file, so I cant understand why you have an Client here. Maybe you could remove them, the code can be this:
public ServerClient(int port) {
Server server = new Server(port);
server.start();
}
as for Client Code
your server socket is 7777 so you should connect 7777 port rather than 8765 in you init method maybe the code can be this:
void init() throws Exception {
s=new Socket(server name,7777);
...
}

Java Sockets - EOFException when trying to implement multi-threading

I think it's because when I multi-thread the client&server, the DataOutputStream and DataInputStream buffers I use get overwritten or something like that since the socket can only have 1 duplex connection.
Here's what I have for now:
Client Class in my client program:
public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException {
for (int i=0;i<2;i++) //change limit on i to change number of threads
{
new Thread(new ClientHandler(i)).start();
}
Thread.sleep(10000);
ClientHandler class in my client program:
(Sends a value to the server, the server will echo it back).
public class ClientHandler implements Runnable {
public int clientNumber;
public ClientHandler(int i){
this.clientNumber=i;
}
public void run() {
Socket socket = null;
try {
socket = new Socket("localhost",9990);
System.out.println("connected client number "+clientNumber);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
output.writeDouble((new Random()).nextDouble());
System.out.println(input.readDouble());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Server Class in my server program:
ServerSocket socket = new ServerSocket(9990);
try {
while (true) {
Socket threadSocket = socket.accept();
new Thread(new ServerHandler(threadSocket)).start();
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
socket.close();
}
}
}
ServerHandler Class in my server program (receives value from client and echoes it back)
public class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
while(true) {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
double a = input.readDouble();
output.writeDouble(a);
}catch (IOException e){
e.printStackTrace();
}
}
}
So it's a pretty straight-forward implementation: create multiple threads of the client, and connect them to multiple threads of the server.
Everything works fine until the line:
double a = input.readDouble();
in my ServerHandler class.
I get an EOFException
I'm guessing it's because there can only be a single duplex connection between sockets. But if that's the case then how would I implement multi-threading of sockets at all?
So my question is: how can I get rid of the EOFException and allow myself to perform multi-threaded client-server socket interaction?
(preferably not changing much about my code because it's taken me a long time to get to this point).
The problem is that you share same Socket variable in ServerHandler for all threads:
private static Socket socket
Remove static keyword. Your ServerHandler will be something like this:
public static class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
double a = input.readDouble();
output.writeDouble(a);
} catch (IOException e) {
e.printStackTrace();
}
}
}

EOFException / SocketException when working with sockets and threads

This socket application works perfectly fine until I add support for multiple client connections to the server. Then I get a EOFException from the client, and a SocketException: Socket closed from the server.
Server.java:
public class Server {
static final int PORT = 8005;
static final int QUEUE = 50;
public Server() {
while (true) {
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE);
Socket socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
output.writeUTF("Hey, this is the server!");
output.flush();
System.out.println(input.readUTF());
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
}
});
thread.start();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java:
public class Client {
static final String HOST = "localhost";
static final int PORT = 8005;
public Client() {
try (Socket socket = new Socket(HOST, PORT);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())
) {
System.out.println(input.readUTF());
output.writeUTF("Hey, this is the client!");
output.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}
A couple problems here:
You're creating a new ServerSocket for each pass through the loop. For a multi-client server you should instead be opening one ServerSocket and calling accept() on it for each client that connects.
Try-with-resources closes all resources it's provided with as soon as the try block is exited. You're creating a Thread that uses output but executes independently of the try block, so the execution flow is leaving the try block before thread finishes executing, resulting in socket (and output) being closed before the thread is able to use them. This is one of those situations where your resources need to be used outside the scope of the try block (in the thread you create to use them), so try-with-resources can't do all your resource handling for you.
I would rearrange your server code to something like:
public class Server {
static final int PORT = 8005;
static final int QUEUE = 50;
public Server() {
// create serverSocket once for all connections
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE)) {
while (true) {
// accept a client connection, not in a try-with-resources so this will have to be explicitly closed
final Socket socket = serverSocket.accept();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// limit scope of input/output to where they're actually used
try (DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
output.writeUTF("Hey, this is the server!");
output.flush();
System.out.println(input.readUTF());
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
// implicitly close socket when done with it
try {
socket.close();
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
}
});
thread.start();
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
Code is commented somewhat to explain some of the moves. Also note that the socket.close() call is in its own try-catch block to ensure that it's called even if the I/O streams throw an exception. It could equivalently (or perhaps more correctly now that I think about it) been placed in a finally block on the I/O stream try-catch block.

Java socket works only for one client, blocked after server accept

I have a problem with my client/server program, which is blocked after one client is connected. My one client can communicate with my server, but when I try to connect another, the second can't connect. I never see my 'ok' on my console:
public class Server{
private Map<Integer,ThreadClient > mapThreads;
private ServerSocket serveur ;
public static void main(String args[])
{
try{
Serveur serv = new Server();
serv.setServer( new ServerSocket(4786,2));
while (true)
{
serv.getMapThreads().put(new ThreadClient(serv.getServer().accept(),serv);
System.out.println("ok");
}
}
catch (Exception e) { }
}
class ThreadClient implements Runnable
{
private Thread t;
private Socket socket;
private ObjectOutputStream oos ;
private ObjectInputStream ois;
private Serveur server;
public ThreadClient(Socket s, Server serv ) throws ClassNotFoundException
{
server = serv;
socket=s;
try{
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
}
catch (IOException e){ }
t = new Thread(this);
t.start();
}
public void run()
{
try
{
while(true){
// send and recev message
}
}
}
catch (Exception e){ }
}
Move the construction of the object streams out of the constructor and into the run() method. The process implies I/O with the peer so it shouldn't be carried out in the accept() thread.

java.io.StreamCorruptedException: invalid stream header: 72657175

Hey I am implementing an electronic voting system based on client server chat.
When I run the server it runs without any problems but without printing as well and also the client. But as soon as I give the input to the client, it gives me the following exception and crashes. Here is the code of the server and the client. So what do u think I should do to start the engine?
package engine;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
public class Server {
ServerSocket server;
int port = 6000;
public Server() {
try {
server = new ServerSocket(6000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleConnection(){
try {
while(true){
Socket connectionSocket;
connectionSocket = server.accept();
new ConnectionHandler(connectionSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.handleConnection();
}
}
class ConnectionHandler implements Runnable {
Socket connectionSocket;
Calendar votingStartTime;
Calendar votingEndTime;
boolean timeUp;
ObjectInputStream inFromClient;
ObjectOutputStream outToClient;
BufferedWriter outToFile;
BufferedReader inFromAdmin;
ArrayList<SingleClient> clients = new ArrayList<SingleClient>();
ArrayList<Candidate> candidates;
this is the part of the code the Exception comes from:
public ConnectionHandler(Socket socket) {
try {
this.connectionSocket = socket;
votingStartTime = new GregorianCalendar();
outToClient = new ObjectOutputStream(
connectionSocket.getOutputStream());
inFromClient = new ObjectInputStream(
connectionSocket.getInputStream());
inFromAdmin = new BufferedReader(new InputStreamReader(System.in));
startVotingSession();
Thread t = new Thread(this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and this is the client's main method the Exception as soon as i give the input:
public static void main(String[] args) throws Exception {
client c = new client();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while(true){
input = br.readLine();
if(input.equals("0")){
c.register();
}else if(input.equals("1")){
c.login();
}else if(input.equals("2")){
c.listCandidates();
}else if(input.equals("3")){
c.vote();
}else if(input.equals("4")){
c.checkResults();
}else if(input.equals("5")){
c.checkFinalResults();
}else if(input.equals("6")){
c.logout();
}else {
break;
}
}
}
}
without seeing the relevant code, i would guess you are recreating the ObjectInputStream on an existing socket InputStream. you must create the object streams once per socket and re-use them until you are completely finished with the socket connection. also, you should always flush the ObjectOutputStream immediately after creation to avoid deadlock.

Categories

Resources