user3870178
user3870178

Reputation: 11

The method Socket(String, int) is undefined for type

I'm trying to get a basic client working to learn Sockets and for some reason, i can't seem to create a Socket object though the docs say it should be able to take a String, int combo. Did I mess up somewhere?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class JokeClient {

    public static void main(String[] args) {
        // Ensures they have to have a length of 2

        int PORT_NUM = 3363;
        String ipAddress = "127.0.0.1";

        if (args.length == 2) {
            PORT_NUM = Integer.parseInt(args[1]);
            ipAddress = args[0];
        } 
        else {
            if (args.length > 0) {
                System.err.println("programName <ipAddress/hostname> <portNum>");
                System.exit(1);
            } 
            else
                System.out.println("Assuming you want defaults of IP Address: " + ipAddress + "\nPort Number: " + PORT_NUM);
        }

        System.out.println("Setting up client...");
        Scanner textIn = new Scanner(System.in);

        try {
            Socket clientSock = Socket(ipAddress, PORT_NUM);
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (Exception e) {
            System.out.println("Error connecting to: " + ipAddress + " on:" + PORT_NUM + "\nError: " + e);
        }
    }
}

The creation of clientSocket is the problem with the instantiation I am trying. Am I using the wrong Socket?

Upvotes: 1

Views: 1467

Answers (1)

M A
M A

Reputation: 72884

Constructing an instance of a class requires the new keyword:

Socket clientSocket = new Socket(ipAddress, PORT_NUM);

Otherwise the compiler will consider it as a normal method instead of a constructor.

Upvotes: 2

Related Questions