gpt4 book ai didi

java - 我发现我的代码在 "socket socket = serverSocket.accept();"之后没有跟随,程序卡在这里

转载 作者:行者123 更新时间:2023-12-01 22:33:33 25 4
gpt4 key购买 nike

图片:

Please view screenshot

我正在尝试在 android 模拟器中进行套接字编程,在两个不同的模拟器上运行客户端和服务器。我发现我的代码在“socket socket = serverSocket.accept();”之后没有跟随,程序卡在这里。我正在使用 ip : 10.0.2.2 作为其他 ip 给出 I/O 异常。另外,我知道 serverSocket.accept() 的作用,我的问题是我无法解决该问题。为什么它总是在等待客户端,即使我的客户端正在尝试连接它。请检查我的服务器和客户端代码,让我知道是否有人可以解决这个问题。

服务器:

package com.example.serverside;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);

infoip.setText(getIpAddress());

Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}

@Override
protected void onDestroy() {
super.onDestroy();

if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

private class SocketServerThread extends Thread {

static final int SocketServerPORT = 8080;
int count = 0;

@Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});

while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});

SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();

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

}

private class SocketServerReplyThread extends Thread {

private Socket hostThreadSocket;
int cnt;

SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}

@Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;

try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();

message += "replayed: " + msgReply + "\n";

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});
}

}

private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();

if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}

}

}

} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}

return ip;
}
}

客户:

package com.example.clientside;

import android.os.Bundle;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;

public class MainActivity extends Activity {

TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;

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

editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);

buttonConnect.setOnClickListener(buttonConnectOnClickListener);

buttonClear.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
textResponse.setText("");
}});
}

OnClickListener buttonConnectOnClickListener =
new OnClickListener(){

@Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};

public class MyClientTask extends AsyncTask<Void, Void, Void> {

String dstAddress;
int dstPort;
String response = "";

MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}

@Override
protected Void doInBackground(Void... arg0) {

Socket socket = null;

try {
socket = new Socket(dstAddress, dstPort);

ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];

int bytesRead;
InputStream inputStream = socket.getInputStream();

/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}

@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}

}

}

最佳答案

实际上并没有卡住......当您的客户端连接时,将执行进一步的代码

在服务器代码中从此代码获取IP地址

public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();

for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}

当您获得 IP 地址后,尝试使用此 IP 和端口 8080 进行连接

关于java - 我发现我的代码在 "socket socket = serverSocket.accept();"之后没有跟随,程序卡在这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58539296/

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