gpt4 book ai didi

java - 与两个 wifip2p 设备建立套接字连接

转载 作者:行者123 更新时间:2023-12-02 04:57:27 26 4
gpt4 key购买 nike

我正在将 wifip2p 设备发现作为服务实现。我已成功发现一个设备,并且其 WifiP2pDevice 实例可用。现在我想建立一个套接字连接。首先,我必须连接到找到的设备

WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = wifiP2pDevice.deviceAddress;
wifiP2pManager.connect(channel, config, listener);

这里我成功连接到对等点。但是当我尝试连接套接字进行数据传输时,我发现我没有正确的 InetAddress 但我尝试使用以下代码

Socket socket = new Socket();
socket.bind(null);
socket.connect( new InetSocketAddress(port), 1000);

正如预期的那样,我连接失败。所以这里最有可能的问题是我没有任何主机名。我尝试查找文档,但找不到任何东西。

简而言之,我有一个对等点连接并拥有其 wifip2pdevice 实例,我将如何建立套接字连接?

最佳答案

用于通过wifip2p在两个设备之间传输和接收数据。需要创建三个线程。每个线程用于客户端、服务器和客户端服务器线程用于传输数据。请参阅完整代码。 MainActivity.java 文件:-

public class MainActivity extends AppCompatActivity {

Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;

WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;

BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;

List<WifiP2pDevice> peers=new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;

static final int MESSAGE_READ=1;

ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;

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

Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what)
{
case MESSAGE_READ:
byte[] readBuff= (byte[]) msg.obj;
String tempMsg=new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});

private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
}else {
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});

btnDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}

@Override
public void onFailure(int i) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final WifiP2pDevice device=deviceArray[i];
WifiP2pConfig config=new WifiP2pConfig();
config.deviceAddress=device.deviceAddress;

mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to "+device.deviceName,Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(int i) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});

btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String msg=writeMsg.getText().toString();
sendReceive.write(msg.getBytes());
}
});
}

private void initialWork() {
btnOnOff=(Button) findViewById(R.id.onOff);
btnDiscover=(Button) findViewById(R.id.discover);
btnSend=(Button) findViewById(R.id.sendButton);
listView=(ListView) findViewById(R.id.peerListView);
read_msg_box=(TextView) findViewById(R.id.readMsg);
connectionStatus=(TextView) findViewById(R.id.connectionStatus);
writeMsg=(EditText) findViewById(R.id.writeMsg);

wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

mManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel=mManager.initialize(this,getMainLooper(),null);

mReceiver=new WiFiDirectBroadCastReviever(mManager, mChannel,this);

mIntentFilter=new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}

WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers))
{
peers.clear();
peers.addAll(peerList.getDeviceList());

deviceNameArray=new String[peerList.getDeviceList().size()];
deviceArray=new WifiP2pDevice[peerList.getDeviceList().size()];
int index=0;

for(WifiP2pDevice device : peerList.getDeviceList())
{
deviceNameArray[index]=device.deviceName;
deviceArray[index]=device;
index++;
}

ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}

if(peers.size()==0)
{
Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_SHORT).show();
return;
}
}
};

WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress=wifiP2pInfo.groupOwnerAddress;

if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner)
{
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed)
{
connectionStatus.setText("Client");
clientClass=new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};

@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}

@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}

public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;

@Override
public void run() {
try {
serverSocket=new ServerSocket(8888);
socket=serverSocket.accept();
sendReceive=new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;

public SendReceive(Socket skt)
{
socket=skt;

try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}

}

@Override
public void run() {
byte[] buffer=new byte[1024];
int bytes;

while (socket!=null)
{
try {
bytes=inputStream.read(buffer);
if(bytes>0)
{
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

public void write(byte[] bytes) {

try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}

}
}

public class ClientClass extends Thread{
Socket socket;
String hostAdd;

public ClientClass(InetAddress hostAddress)
{
hostAdd=hostAddress.getHostAddress();
socket=new Socket();
}

@Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive=new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

WiFiDirectBroadCastReviever.java class:
public class WiFiDirectBroadCastReviever extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;

public WiFiDirectBroadCastReviever(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}

@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if (state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"wifi is on",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"wifi is off",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
if (mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
}else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
if (mManager==null){
return;
}

NetworkInfo networkInfo=intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else {
mActivity.connectionStatus.setText("device disconnected");
}
}else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
}
}
}

关于java - 与两个 wifip2p 设备建立套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56404564/

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