[英]Socket android client PC server
我在將Android客戶端連接到PC服務器時遇到問題,這里有代碼
-> PC服務器:
public class Server {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException
{
ServerSocket server = new ServerSocket(4444);
System.out.println("Waiting for clients to connect...");
while (true)
{
Socket s = server.accept();
InetAddress clientAddress = s.getInetAddress();
System.out.println("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]");
s.close();
}
}
}
--->安卓客戶端:
public class Main extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.connect);
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
try {
Socket client = new Socket("10.0.2.2", 4444); //connect to server
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
在我的android設備上,我單擊服務器程序(PC)中的按鈕時無法查看設備連接...為什么? 我試圖插入
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
進入我的AndroidManifest,但是當我單擊按鈕程序崩潰時,Android設備和PC連接到同一網絡(路由器DSL)。
請幫幫我
10.0.2.2是一個地址,供您在模擬器中運行的應用程序用來與PC上運行的服務器連接。 仿真器在同一台PC上。 如果使用真正的設備,則必須使用與設備位於同一WLAN中的PC的(W)LAN地址。 通常類似192.168.0.12。 用ipconfig查找。
您的套接字聲明應如下所示:
Socket client = new Socket(10.0.2.2, 4444); //Quotes removed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.