@Java/Android Socket failed to read message -
i have trouble java sockets.
i need connect server , client through local network , there can more 2 devices connected router client must find out address of server.
the way know solve problem 3 first numbers of clients ip(v4)-address , loop every of 254 other possible ips. (i know way slow , may cause many problems. if know alternative, glad).
actually client android smartphone can dhcp-info.
the problem is, read command check if device server last forever.
if need code, here is!
code:
oncreate:
final wifimanager manager = (wifimanager) super.getsystemservice(wifi_service); final dhcpinfo dhcp = manager.getdhcpinfo(); final string address = inttoip(dhcp.ipaddress); string addresspart=address.substring(0, address.lastindexof('.')+1); arraylist<hashmap<string, string>> l = null; log.d("keyboard","initiating search"); try { l = new checkconnections().execute(addresspart).get(); } catch (interruptedexception e1) { e1.printstacktrace(); } catch (executionexception e1) { e1.printstacktrace(); }
checkconnections:
arraylist<hashmap<string,string>> l=new arraylist<hashmap<string,string>>(); for(int i=1;i<=255;i++){ try { worksocket=new socket(addresspart[0]+i,61927); workout=new bufferedoutputstream(worksocket.getoutputstream()); workin=new bufferedinputstream(worksocket.getinputstream()); byte[] buffer=new byte[6]; workin.read(buffer);//at point app freezes until stop serverside program string answer=new string(buffer,"utf-8"); log.i("keyboard","welcome message: "+answer); if(answer.equalsignorecase("sdk on")){ hashmap<string,string> hm=new hashmap<string,string>(); hm.put("address",addresspart[0]+i); l.add(hm); workout.write(inttobytes(8)); workout.write("closing".getbytes("utf-8")); worksocket.close(); continue; } else{ log.d("keyboard","no sdk-programm detected"); worksocket.close(); continue; } } catch (unknownhostexception e) { log.d("keyboard",addresspart[0]+i+" doesn't exists"); continue; } catch ( interruptedioexception e){ log.w("system.warn",e.getcause()+e.getlocalizedmessage()); log.d("keyboard","timeout"); continue; } catch (ioexception e) { log.d("keyboard",addresspart[0]+i+" doesn't exists"); e.printstacktrace(); continue; } } return l;
the server's code:
serversocket serversocket = new serversocket(61927); system.out.println("socket initiated"); socket client = serversocket.accept(); bufferedinputstream in=new bufferedinputstream(client.getinputstream()); bufferedoutputstream out=new bufferedoutputstream(client.getoutputstream()); system.out.println("client found"); byte[] buffer=new byte[11]; out.write("sdk on".getbytes("utf-8")); in.read(buffer); string s=new string(buffer,"utf-8"); if(!s.equals("got info")){ system.out.println("no sdk client"); client.close(); serversocket.close(); new main(); }
uh, think should ping broadcast-ip , listen answers instead...
android's linux runtime allows read ip answer coming.
Comments
Post a Comment