Android客户端套接字正在连接,但服务器套接字不接受?
我正在尝试通过wifi连接两台android设备并发送一些数据。在客户端,套接字显示已连接,但服务器未在接受之前移动。我甚至不知道这怎么可能。下面是我的服务器和客户端代码。我已使用其中一台设备上运行的wifi热点连接了这两台设备 服务器端:Android客户端套接字正在连接,但服务器套接字不接受?,android,sockets,client-server,client,Android,Sockets,Client Server,Client,我正在尝试通过wifi连接两台android设备并发送一些数据。在客户端,套接字显示已连接,但服务器未在接受之前移动。我甚至不知道这怎么可能。下面是我的服务器和客户端代码。我已使用其中一台设备上运行的wifi热点连接了这两台设备 服务器端: try { ServerSocket servsock = new ServerSocket(4149); Log.d("VR","Waiting"); tex
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
}
客户端:
试一试{
您自己的评论说,代码在接受后到达行,因此我不知道您在问什么。但是,您的复制循环应该如下所示:
while ((count = in.read(buffer)) >= 0)
{
out.write(buffer, 0, count);
}
在写入任何输出之前,没有理由通过将所有输入读入一个巨大的缓冲区或ByteArrayInputStream来引入延迟和浪费内存。“缓冲区”可以是任何合理的大小,例如2k。我设法解决了这个问题。.没有服务器IP地址可供使用。.出于某种原因,android 4.2没有将套接字绑定到设备IP地址…当我试图在姜饼上运行相同的代码时,它起了作用。我得出结论,jelly bean不再支持套接字编程。可能是谷歌迫使我们使用wifidirect api来实现临时联网,而不是服务器-客户端编程。嗨,谢谢你的回复。。这是一个键入错误。。服务器不接受由于某些原因,我无法理解为什么会出现连接问题。我还想补充一点,当在pc上运行与java代码相同的代码时,它是有效的。在android中,我添加了所有权限,并且代码在活动中运行。没有任何线程。@nitinsh99如果它“不接受连接”,它如何在ac之后到达该行接受电话?
while ((count = in.read(buffer)) >= 0)
{
out.write(buffer, 0, count);
}