在用安卓手機(jī)做socket通信的時候,出現(xiàn)這個報錯 java.net.SocketException: socket failed: EACCES (Permission denied),以后不用看就知道網(wǎng)絡(luò)權(quán)限沒有加。
服務(wù)端代碼如下:
public class SocketServer {
public static void main(String[] args) throws IOException {
//1.創(chuàng)建一個服務(wù)器端Socket,即ServerSocket,指定綁定的端口,并監(jiān)聽此端口
ServerSocket serverSocket = new ServerSocket(12345);
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
Socket socket = null;
//2.調(diào)用accept()等待客戶端連接
System.out.println("~~~服務(wù)端已就緒,等待客戶端接入~,服務(wù)端ip地址: " + ip);
socket = serverSocket.accept();
//3.連接后獲取輸入流,讀取客戶端信息
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
is = socket.getInputStream(); //獲取輸入流
isr = new InputStreamReader(is,"UTF-8");
br = new BufferedReader(isr);
String info = null;
while((info=br.readLine())!=null){
//循環(huán)讀取客戶端的信息
System.out.println("客戶端發(fā)送過來的信息" + info);
}
socket.shutdownInput();//關(guān)閉輸入流
socket.close();
}
客戶端代碼如下:我跑在安卓手機(jī)上
private void acceptServer() throws IOException {
//1.創(chuàng)建客戶端Socket,指定服務(wù)器地址和端口
Socket socket = new Socket("xxx", 12345);
//2.獲取輸出流,向服務(wù)器端發(fā)送信息
OutputStream os = socket.getOutputStream();//字節(jié)輸出流
PrintWriter pw = new PrintWriter(os);//將輸出流包裝為打印流
//獲取客戶端的IP地址
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
pw.write("客戶端:~" + ip + "~ 接入服務(wù)器??!");
pw.flush();
socket.shutdownOutput();//關(guān)閉輸出流
socket.close();
}
xxx替換為自己的服務(wù)器的ip,保證手機(jī)和服務(wù)器在同一個網(wǎng)段即可。