gpt4 book ai didi

java - Android 和 java 套接字。套接字连接尝试多次才成功

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:56 24 4
gpt4 key购买 nike

我正在尝试进入物联网领域,并希望让应用程序将字符串从 Android 手机发送到 Linux 电脑。该应用程序通过实现异步任务来实现此目的:

//From the java docs, slightly modified
private Void sendThroughSocket(String s, String host, int port) {
Log.d("E", "In send through socket");
final String hostName = host;//Host is the address of the receiver, can be IP or domain
int portNumber = port;
//Check if device is connected to internet

try {
Socket clientsocket = new Socket(hostName, portNumber); //one of 2-way point communication
Log.d("E", "Created Socket: ");
DataOutputStream DOS = new DataOutputStream(clientsocket.getOutputStream());
if (clientsocket.isConnected())
Log.d("E", "Socket connected");
DOS.writeUTF(s);
clientsocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
new Runnable() {
public void run() {
Toast.makeText(context, "Don't know about host " + hostName, Toast.LENGTH_SHORT).show();
}
};

} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
//Toast can not be run using asynctask since it acesses UI
new Runnable() {
public void run() {
Toast.makeText(context, "Couldn't get I/O for the connection to " + hostName + " , check the port", Toast.LENGTH_SHORT).show();
}
};

} catch (Exception e) {
Log.d("E", "#fares" + e.getClass().getName().toString());

}
return null;
}

我有 3 次尝试发送字符串,所有这些都是从我的搜索栏触发的(我将搜索栏进度值作为我的字符串发送):公共(public)无效onProgressChanged(SeekBareekBar,int i, boolean b)公共(public)无效onStartTrackingTouch(SeekBareekBar)公共(public)无效onStopTrackingTouch(SeekBareekBar)

所有 3 个的实现都是相同的: 公共(public)无效onProgressChanged(SeekBareekBar,int i, boolean b){

                    progressvalue = i;
textView.setText("Brightness = " + progressvalue + " %");


if (((RecieverPort.equals("Please enter port Number")) || (RecieverIP.equals("Please enter receiver IP")))) {

//Make sure toast isn't persistent
if (IPPortToastcount++ == 0)
Toast.makeText(MainActivity.this, "Please set both IP and Port ", Toast.LENGTH_SHORT).show();

} else {
//Check if connected to internet
if (!isConnectedtoInternet(MainActivity.this)) {
if (ConnectivityToastCount++ < 1)
Toast.makeText(MainActivity.this, "You are not connected to the Internet", Toast.LENGTH_SHORT).show();
} else {
//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);


}

}


}

主要

//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);

服务器端(我的电脑)非常简单:

int portNumber =  44339; // Choose unused port on router
//Open a socket

try {

//System.out.println("in try statement");
try (ServerSocket serverSocket1 = new ServerSocket(portNumber)) {
portNumber = serverSocket1.getLocalPort();
System.out.println("Created socket at port " + portNumber);
Socket clientSocket = serverSocket1.accept();

System.out.println("Accepted");

DataInputStream DIS = new DataInputStream(clientSocket.getInputStream()); //get input from socket
//System.out.println("Created reader");

String inputLine;


// System.out.println("About to read");


while (DIS.available() > 0) {
inputLine = DIS.readUTF();
System.out.println(inputLine);
}


}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getClass().getSimpleName());
}

这种方法是有效的,只是在接受服务器套接字之前需要很长时间(秒)。它也只适用于 onprogresschanged ,这让我相信多次尝试

//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);
在成功创建套接字并连接到电脑之前需要

。如何确保一次点击或一次调用函数就足以发送字符串?抱歉发了这么长的帖子,但这是我第一次问:)

编辑:我的新服务器代码:

try {

//System.out.println("in try statement");
try ( ServerSocket serverSocket1 = new ServerSocket(portNumber))
{
portNumber = serverSocket1.getLocalPort();
System.out.println("Created socket at port " + portNumber);
while(true){
Socket clientSocket = serverSocket1.accept();

// System.out.println("Accepted");

DataInputStream DIS = new DataInputStream(clientSocket.getInputStream()); //get input from socket
//System.out.println("Created reader");

//String inputLine;


//System.out.println("About to read");
System.out.println(DIS.readUTF());


}


}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getClass().getSimpleName());
}

值得注意的是,即使在 while true 循环中,服务器也总是会显示 4 个数字然后停止。

编辑:这是一个示例日志:10-06 20:08:09.145 26372-26372/com.example.fares.ledslider D/E:测试方法值中的#fares = 5010-06 20:08:26.475 26372-26372/com.example.fares.ledslider D/E:#Fares 开始跟踪10-06 20:08:26.722 26372-27004/com.example.fares.ledslider D/E: #fares 套接字已连接10-06 20:08:26.810 26372-26764/com.example.fares.ledslider D/E: #fares 套接字已连接10-06 20:08:27.241 26372-27003/com.example.fares.ledslider D/E: #fares 套接字已连接10-06 20:08:27.304 26372-26372/com.example.fares.ledslider D/E:停止跟踪中的#fares

最佳答案

ST.cancel() 可以删除。另外,不等待可用性看起来也不太好。

关于java - Android 和 java 套接字。套接字连接尝试多次才成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568896/

24 4 0
文章推荐: javascript - 将我的搜索过滤器链接到列表项 : knockout js
文章推荐: python - 使用 minidom 获取指定 中的 HTML 链接