Getting connection errors when creating server / client chat program in java

I haven't worked anywhere with this project, but I'm just trying to make sure everything works, more specifically that the client and server are connecting and I am getting connection errors. Here are my two programs. I'm also not really sure how to run both of them at once in eclipse, so maybe this is the problem. Any help is greatly appreciated

import java.net.*;
import java.util.*;
import java.io.*;

public class Server {



public  void main(String[] args)throws Exception {

    ServerSocket server = new ServerSocket(3333);;

    while (true)
    {
        Socket clientsocket = server.accept();
        Scanner sc = new Scanner(clientsocket.getInputStream());
        PrintStream p = new PrintStream(clientsocket.getOutputStream());
        String message = "Hello from server";
        p.print(message);
    }

}

      

And heres a client

    public static void main(String[] args)throws Exception {
    Client display = new Client();
    display.setVisible(true);

    try {
    Socket server = new Socket("localhost", 3333);
    Scanner sc = new Scanner(server.getInputStream());
    PrintStream p = new PrintStream(server.getOutputStream());
    System.out.println(sc.next());

    server.close();
    sc.close();
    p.close();


    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

      

I have the gui stuff above and below the client that I didn't show. When I run them I get the following errors:

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 Client.main(Client.java:56)

      

and line 56 is line with: - Socket server = new Socket ("localhost", 3333);

+3


source to share





All Articles