www.91084.com

GVKun编程网logo

Android java.net.SocketException:权限被拒绝(权限被拒绝是什么意思)

10

在这篇文章中,我们将带领您了解Androidjava.net.SocketException:权限被拒绝的全貌,包括权限被拒绝是什么意思的相关情况。同时,我们还将为您介绍有关Androidio.soc

在这篇文章中,我们将带领您了解Android java.net.SocketException:权限被拒绝的全貌,包括权限被拒绝是什么意思的相关情况。同时,我们还将为您介绍有关Android io.socket.SocketIOException: Error while handshaking、Android java.net.SocketException:socket failed:EACCES(Permission denied)、Android java.net.SocketTimeoutException:连接超时、android mina 客户端连接抛 java.net.SocketException: Tra...的知识,以帮助您更好地理解这个主题。

本文目录一览:

Android java.net.SocketException:权限被拒绝(权限被拒绝是什么意思)

Android java.net.SocketException:权限被拒绝(权限被拒绝是什么意思)

如何解决Android java.net.SocketException:权限被拒绝?

我是一名Android初学者。 我想创建一个ServerSocket,但是它总是在“ serverSocket = new ServerSocket(12345);”行上调用“ java.net.socketException:权限被拒绝”。 我想知道为什么,谢谢。

ServerThread.java

public class ServerThread extends Thread {
    ServerSocket serverSocket ;
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(12345);
            while(true) {
                System.out.println("IN");
                Socket socket = serverSocket.accept(); // null
            }
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ServerThread().start();
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Android io.socket.SocketIOException: Error while handshaking

Android io.socket.SocketIOException: Error while handshaking

这个是 nodejs 官网的 demo,在 android 模拟器中运行出错了

package com.ewell.websocket;



import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;


public class PomeloClient {


private static final Logger logger = Logger.getLogger("org.netease.pomelo");
private final static String URLHEADER = "http://";
private final static String JSONARRAY_FLAG = "[";
private int reqId;
private SocketIO socket;
private Map<Integer, DataCallBack> cbs;
private Map<String, List<DataListener>> listeners;

private JSONObject _users = null;

public PomeloClient(String url, int port) {
initSocket(url, port);
cbs = new HashMap<Integer, DataCallBack>();
listeners = new HashMap<String, List<DataListener>>();
}


/**
* Init the socket of pomelo client.

* @param url
* @param port
*/
private void initSocket(String url, int port) {
StringBuffer buff = new StringBuffer();
if (!url.contains(URLHEADER))
buff.append(URLHEADER);
buff.append(url);
buff.append(":");
buff.append(port);
try {
socket = new SocketIO(buff.toString());
} catch (MalformedURLException e) {
throw new RuntimeException("please check your url format.");
}
}


/**
* Initialize pomelo client.

*/
public void init() {
socket.connect(new IOCallback() {
public void onConnect() {
logger.info("pomeloclient is connected.");
}


public void onMessage(JSONObject json, IOAcknowledge ack) {
logger.warning("pomelo send message of string.");
}


// get messages from the server side
public void onMessage(String data, IOAcknowledge ack) {
if (data.indexOf(JSONARRAY_FLAG) == 0) {
processMessageBatch(data);
} else {
processMessage(data);
}
}


public void onError(SocketIOException socketIOException) {
logger.info("connection is terminated.");
emit("disconnect", null);
socket = null;
socketIOException.printStackTrace();
}


public void onDisconnect() {
logger.info("connection is terminated.");
emit("disconnect", null);
socket = null;
}


public void on(String event, IOAcknowledge ack, Object... args) {
logger.info("socket.io emit events.");
}


});
}


/**
* Send message to the server side.

* @param reqId
*            request id
* @param route
*            request route
* @param msg
*            reqest message
*/
private void sendMessage(int reqId, String route, JSONObject msg) {
socket.send(Protocol.encode(reqId, route, msg));
}


/**
* Client send request to the server and get response data.

* @param args
*/
public void request(Object... args) {
if (args.length < 2 || args.length > 3) {
throw new RuntimeException("the request arguments is error.");
}
// first argument must be string
if (!(args[0] instanceof String)) {
throw new RuntimeException("the route of request is error.");
}


String route = args[0].toString();
JSONObject msg = null;
DataCallBack cb = null;


if (args.length == 2) {
if (args[1] instanceof JSONObject)
msg = (JSONObject) args[1];
else if (args[1] instanceof DataCallBack)
cb = (DataCallBack) args[1];
} else {
msg = (JSONObject) args[1];
cb = (DataCallBack) args[2];
}
msg = filter(msg);
reqId++;
cbs.put(reqId, cb);
sendMessage(reqId, route, msg);
}


/**
* Notify the server without response

* @param route
* @param msg
*/
public void inform(String route, JSONObject msg) {
request(route, msg);
}


/**
* Add timestamp to message.

* @param msg
* @return msg
*/
private JSONObject filter(JSONObject msg) {
if (msg == null) {
msg = new JSONObject();
}
long date = System.currentTimeMillis();
try {
msg.put("timestamp", date);
} catch (JSONException e) {
e.printStackTrace();
}
return msg;
}


/**
* Disconnect the connection with the server.
*/
public void disconnect() {
socket.disconnect();
}


/**
* Process the message from the server.

* @param msg
*/
private void processMessage(String msg) {
int id;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(msg);
// request message
if (jsonObject.has("id")) {
id = jsonObject.getInt("id");
DataCallBack cb = cbs.get(id);
cb.responseData(jsonObject.getJSONObject("body"));
cbs.remove(id);
}
// broadcast message
else
emit(jsonObject.getString("route"), jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}


/**
* Process message in batch.

* @param msgs
*/
private void processMessageBatch(String msgs) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(msgs);
for (int i = 0; i < jsonArray.length(); i++) {
processMessage(jsonArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}


/**
* Add event listener and wait for broadcast message.

* @param route
* @param listener
*/
public void on(String route, DataListener listener) {
List<DataListener> list = listeners.get(route);
if (list == null)
list = new ArrayList<DataListener>();
list.add(listener);
listeners.put(route, list);
}


/**
* Touch off the event and call listeners corresponding route.

* @param route
* @param message
* @return true if call success, false if there is no listeners for this
*         route.
*/
private void emit(String route, JSONObject message) {
List<DataListener> list = listeners.get(route);
if (list == null) {
logger.warning("there is no listeners.");
return;
}
for (DataListener listener : list) {
DataEvent event = new DataEvent(this, message);
listener.receiveData(event);
}
}

在 xml 加了权限 <uses-permission android:name="android.permission.INTERNET"/>

socket.connect () 的时候 进入 onError(SocketIOException socketIOException)socketIOException 为 io.socket.SocketIOException: Error while handshaking

不知道什么原因?

}

Android java.net.SocketException:socket failed:EACCES(Permission denied)

Android java.net.SocketException:socket failed:EACCES(Permission denied)

嗨,我得到一个 Android应用程序,但是当我启动它,我的控制台中出现错误.我正在使用Datagram套接字创建一个连接,而我正在使用2类:MainActivity(它是应用程序的主要活动)和UdpClientServer来创建连接.

这里代码MainActivity:

public class MainActivity extends Activity {

private UdpClientServer cu;
private EditText textIpScheda;
private EditText textUdpPort;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textIpScheda = (EditText) findViewById(R.id.textIpScheda);
    textUdpPort = (EditText) findViewById(R.id.textUdpPort);


    try {
        cu = new UdpClientServer(this);
    } catch (IOException e) {
        e.printstacktrace();
    }
}

public EditText getTextIpScheda(){
    return textIpScheda;
}

public void setTextIpScheda(EditText textIpScheda){
    this.textIpScheda = textIpScheda;
}

public EditText getTextUdpPort() {
    return textUdpPort;
}

public void setTextUdpPort(EditText textUdpPort) {
    this.textUdpPort = textUdpPort;
}

这里代码UdpClientServer:

public class UdpClientServer {

public static String sReceive;
private static DatagramSocket dSocket;
int receiveBufferSize = 1024;
int portUdp = 0;
final String PINGACMD = "AT*PINGA001";
InetAddress ipScheda;

byte[] receiveData = new byte[receiveBufferSize];
private MainActivity gui = null;

public UdpClientServer(MainActivity gui) throws SocketException,IOException {
    this.gui = gui;

    portUdp = Integer.parseInt(String.valueOf(gui.getTextUdpPort().getText()));
    dSocket = new DatagramSocket(portUdp);
}

public void run(){
    while (true) {
        // svuotamento buffer
        Arrays.fill(receiveData,(byte) 0);
        DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);

        try {
            dSocket.receive(receivePacket);
        } catch (IOException e) {
            e.printstacktrace();
        }
        ipScheda = receivePacket.getAddress();
        int port = receivePacket.getPort();
        gui.getTextUdpPort().setText("" + port);
        gui.getTextIpScheda().setText(ipScheda.getHostAddress());

        sReceive = new String(receivePacket.getData());
        this.sendCommand(PINGACMD);
    }

}

public void sendCommand(String outSentence){

    byte[] sendData = outSentence.getBytes();

    DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,ipScheda,portUdp);

    try {
        dSocket.send(sendPacket);
        Thread.sleep(100);
    } catch (IOException e) {
        e.printstacktrace();
    } catch (InterruptedException e) {
        e.printstacktrace();
    }
    finally {
    }
}

}

这里的logcat:

12-29 11:43:22.291  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ java.net.socketException: socket Failed: EACCES (Permission denied)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:623)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:93)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at java.net.DatagramSocket.createSocket(DatagramSocket.java:157)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at java.net.DatagramSocket.<init>(DatagramSocket.java:80)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at com.example.matteo.myfirstapp.UdpClientServer.<init>(UdpClientServer.java:32)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at com.example.matteo.myfirstapp.MainActivity.onCreate(MainActivity.java:24)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5933)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2251)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:144)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5221)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ Caused by: android.system.ErrnoException: socket Failed: EACCES (Permission denied)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at libcore.io.Posix.socket(Native Method)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:282)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:608)
12-29 11:43:22.294  28914-28914/com.example.matteo.myfirstapp W/System.err﹕ ... 18 more

在我的AndroidManifest.xml中刚刚添加了字符串

<uses-permission android:name="android.permission.INTERNET"/>

但它不行

你可以帮我吗?
谢谢

解决方法

尝试添加以下内容:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Android java.net.SocketTimeoutException:连接超时

Android java.net.SocketTimeoutException:连接超时

最近,我在程序中遇到以下错误:

11-18 12:30:30.259: W/System.err(21368): java.net.SocketTimeoutException: Connection timed out
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
11-18 12:30:30.259: W/System.err(21368):    at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
11-18 12:30:30.259: W/System.err(21368):    at java.net.Socket.connect(Socket.java:1002)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:75)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)
11-18 12:30:30.269: W/System.err(21368):    at com.example.simplevider.SimpleVideo$4.run(SimpleVideo.java:122)
11-18 12:30:30.279: W/System.err(21368):    at java.lang.Thread.run(Thread.java:1019)

产生此错误的函数如下:

    private void sendStuff() {
    Log.e("sendStuff","======================================");
    new Thread(new Runnable() {

        @Override
        public void run() {
            final int BUFFER_SIZE = 4096;
            try {
                File uploadFile = new File(existingFileName);
                System.out.println("File to upload: " + existingFileName);
                URL url = new URL(URL);

                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setUseCaches(false);
                httpConn.setDoOutput(true);
                httpConn.setRequestMethod("POST");
                httpConn.setReadTimeout(60*1000);
                httpConn.setConnectTimeout(60 * 1000);
                // sets file name as a HTTP header
                httpConn.setRequestProperty("fileName",uploadFile.getName());
                httpConn.setRequestProperty("extra-id",uploadFile.getAbsoluteFile().toString());
                httpConn.setRequestProperty("extra-id2",uploadFile.getParent());
                httpConn.setRequestProperty("extra-id3",uploadFile.length() + "");



                OutputStream outputStream = httpConn.getOutputStream(); //<< this is the source of the error


                FileInputStream inputStream = new FileInputStream(uploadFile);

                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = -1;

                System.out.println("Start writing data...");

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer,bytesRead);
                }

                System.out.println("Data was written.");
                outputStream.close();
                inputStream.close();

                // always check HTTP response code from server
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // reads server's response
                    BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                    String response = reader.readLine();
                    System.out.println("Server's response: " + response);
                } else {
                    System.out.println("Server returned non-OK code: " + responseCode);
                }

            } catch (Exception e) {
                e.printStackTrace();
                sendStuff();
            }

        }
    }).start();

}

该功能在普通的JAVA中可以正常使用,但是当它复制到Android时会强制转换java.net.SocketTimeoutException: Connection timed out,我不知道为什么。

android mina 客户端连接抛 java.net.SocketException: Tra...

android mina 客户端连接抛 java.net.SocketException: Tra...

mina 在网络不可用时抛 java.net.SocketException: Transport endpoint is not connected 异常,session.isConnected () 仍然返回 true,导致判断有误。解决方法:执行 Thread.sleep (200) 休眠一段时间再调用 session.isConnected() 作判断。

关于Android java.net.SocketException:权限被拒绝权限被拒绝是什么意思的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Android io.socket.SocketIOException: Error while handshaking、Android java.net.SocketException:socket failed:EACCES(Permission denied)、Android java.net.SocketTimeoutException:连接超时、android mina 客户端连接抛 java.net.SocketException: Tra...的相关知识,请在本站寻找。

本文标签: