方法Socket(String,int)未定义类型

时间:2014-07-23 19:12:36

标签: java sockets

我试图让一个基本的客户端工作来学习套接字,出于某种原因,我似乎无法创建一个Socket对象,尽管文档说它应该能够采用String,int combo 。我在某个地方搞砸了吗?

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);
        }
    }
}

clientSocket的创建是我正在尝试的实例化的问题。我使用错误的套接字吗?

1 个答案:

答案 0 :(得分:2)

构建类的实例需要new关键字:

Socket clientSocket = new Socket(ipAddress, PORT_NUM);

否则编译器会将其视为普通方法而不是构造函数。