Java.lang.IllegalArgumentException:host = null,port = 4444

时间:2015-03-31 13:06:32

标签: android server

如果我在模拟器中运行我的应用程序,我的应用程序会立即崩溃。我收到错误'引起:java.lang.IllegalArgumentException:host = null,port = 4444。' Logcat说错误来自InetSocketAdress。这是我的服务器代码:

  package com.imptmd.charliemacdonald.desleutelaar_v3;

 import android.os.AsyncTask;
 import android.util.Log;

 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
 import java.net.UnknownHostException;

 /**
 * Created by Charlie on 26-3-2015.
 */
 public class Server extends AsyncTask<Void, Void, String> {

private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;

public Server(String ip, int port, String message ) {
    super();
    //IP, Port en bericht om naar server te sturen
    this.message = message;
    this.ip = ip;
    this.port = port;
}

@Override
protected String doInBackground(Void... params) {
    try {
        Socket serverSocket = new Socket();
        serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);

        this.sendMessage(message, serverSocket);

        InputStream input;

        try {
            input = serverSocket.getInputStream();
            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            responseStreamReader.close();

            this.serverResponse = stringBuilder.toString();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        System.out.println("Response: " + serverResponse);

    } catch (UnknownHostException e) {
        Log.d("debug", "can't find host");
    } catch (SocketTimeoutException e) {
        Log.d("debug", "time-out");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return serverResponse;
}

private void sendMessage(String message, Socket serverSocket) {
    OutputStreamWriter outputStreamWriter = null;

    try {
        outputStreamWriter = new     OutputStreamWriter(serverSocket.getOutputStream());
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    if (outputStreamWriter != null) {
        BufferedWriter bufferedWriter = new      BufferedWriter(outputStreamWriter);
        PrintWriter writer = new PrintWriter(bufferedWriter, true);

        writer.println(message);
    }
}
}

用户可以填写IP的类的代码:

 package com.imptmd.charliemacdonald.desleutelaar_v3;

 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.KeyEvent;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;

 import org.json.JSONException;
 import org.json.JSONObject;

 import java.util.concurrent.ExecutionException;


 public class GebruikerIP extends Activity {

private Boolean serverCheck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTitle("Slotenbedrijf De Sleutelaar");

    //Check voor internet verbinding
    if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
    {
    }
    else
    {
        Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gebruikerip);

    Button ipButton = (Button) findViewById(R.id.serverbutton);
    ipButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            verbindServer();
        }

    });

    //Enter key afvangen
    EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
    ipInvoer.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {

            switch(keyCode) {
                case KeyEvent.KEYCODE_ENTER:
                    verbindServer();
                    break;

                default:
                    return false;
            }

            return true;

        }
    });

}

//server connectie maken voor ophalen van diensten
public void verbindServer() {
    TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
    String ip = ipVeld.getText().toString();
    Log.i("ip", ip);

    String response = null;
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("slotenlijst", "");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        try {
            response = new Server(ip,
                    4444, jsonObject.toString()).execute().get();
            //exceptions afvangen
        } catch (InterruptedException e)
        {

        }
    } catch (ExecutionException e1)
    {

    }
    if (response == null) {
        serverCheck = false;
        Toast.makeText(this, "Verbinden met server mislukt, staat server    aan?", Toast.LENGTH_LONG).show();

    } else {
        //doorgaan naar MainActivity
        serverCheck = true;
        HoofdschermFragment.serverIp = ip;
        Intent startApp = new Intent(this, MainActivity.class);
        startActivity(startApp);

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_gebruiker_ip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    return super.onOptionsItemSelected(item);
}
}

我无法找到如何修复此错误。帮助我会感激。谢谢!

1 个答案:

答案 0 :(得分:1)

将其更改为

InetAddress inetServer = InetAddress.getByName(IP);

大于

Socket socket = new Socket(inetServer, devicePort);

如果您使用的是Server Socket而不是使用下面的行

ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);