gpt4 book ai didi

java - 如何使用套接字将移动应用程序从您的 Android 移动设备连接到您的笔记本电脑服务器?

转载 作者:太空狗 更新时间:2023-10-29 14:29:08 25 4
gpt4 key购买 nike

我有一个在笔记本电脑上运行的非常简单的 Java 服务器。另一方面,我的平板电脑也有一个非常简单的客户端连接到我的服务器,但它不工作。两者都在同一个无线网络上运行。

服务器示例 ServerSocket serverSocket = null; 套接字套接字=空; 数据输入流 dataInputStream = null; DataOutputStream dataOutputStream = null;

    try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");

简单的客户端代码:

mysock = new Socket(server_adress, port_number);

我试过设置 list WIFI 权限。尝试关闭计算机防火墙。关于无线连接如何工作可能会阻止连接,我应该知道什么吗?

提前致谢

最佳答案

您需要设置互联网权限。

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

客户端:

String adresaServer = "192.168.4.120";

int PORT = 8095;
Socket socket = null;

DataInputStream in = null;

try {
socket = new Socket();
SocketAddress adr = new InetSocketAddress(adresaServer, PORT);
socket.connect(adr, 1500);

out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
out.flush();
} catch (SocketTimeoutException e) {
System.err.println(" Error at CONNECTINGG: \n" + e);

} catch (UnknownHostException e) {
System.err.println(" Serverul nu poate fi gasit \n" + e);
System.exit(1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
out.writeFloat(sensors.getValueGyroZ());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {

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

服务器端:

ServerSocket serverSocket = null;

try {
serverSocket = new ServerSocket(PORT);
serverSocket.setSoTimeout(1600000);

System.out.println(" Waiting a client ... ");
Socket socket = serverSocket.accept();
int i = 0;
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());



while (true) {


DataInputStream in = new DataInputStream(
socket.getInputStream());



System.out.println(String.valueOf(in.readFloat()));

}

} catch (IOException e) {
System.err.println(" Eroare IO \n" + e);


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

}

关于java - 如何使用套接字将移动应用程序从您的 Android 移动设备连接到您的笔记本电脑服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8562419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com