我想通過wifi連接兩個android設備併發送一些數據。在客戶端,套接字顯示已連接,但服務器未超出接受範圍。我甚至不確定這是可能的。以下是我的服務器和客戶端代碼。我已連接使用設備上運行的WiFi熱點的兩個設備。Android客戶端套接字正在連接,但服務器套接字不接受?
服務器端:
try
{
ServerSocket servsock = new ServerSocket(4149);
Log.d("VR","Waiting");
text.setText("waiting"); //code reaching upto here
Socket sock = servsock.accept();
//System.out.println("Accepted connection11 : " + sock);
text.setText("this is acc"+servsock);
//Log.d("VR","Accepted");
text.setText("accepted");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("/sdcard/WebOffice.jpg"); // destination path and name of file
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
Log.d("VR","Socket closed");
Log.d("VR","image should be loaded by now");
text.setText("image should be loaded by now");
Intent i = new Intent(this,ImageDisplay.class);
startActivity(i);
}
catch (Exception e) {
// TODO: handle exception
}
客戶端:
嘗試{
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
ip = et.getText().toString();
sock = new Socket("192.168.43.182",4149);
status.setText("connecting");
status.setText("connected"+sock);
System.out.println("Connecting...");
// sendfile
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
//Intent i = new Intent(Sender.this,ImageReceive.class);
//startActivity(i);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
嗨,謝謝你的回覆。 .that是一個打字錯誤..服務器不接受連接出於某種原因,我無法弄清楚爲什麼。我還想補充說,當相同的代碼作爲java代碼運行在pc上時,它會工作..在android中,我添加了所有權限,並且代碼在一個活動中運行..沒有任何線程。 – nitinsh99 2013-04-22 00:49:18
@ nitinsh99如果它'不接受連接',它在accept()調用後如何到達該行? – EJP 2013-04-24 10:36:23