我想在 2 个 android 设备之间建立通信。使用服务器到客户端(通过服务器)方法。所以通常我在考虑将文件发送到服务器(pc)然后在服务器上获取文件并发送到另一个设备。所以我正在工作第二部分,试图将文件从 pc 发送到 android。但由于某种原因,客户端无法连接到服务器。这是我的代码;
public class TCPServer extends Thread {
public static final int SERVERPORT = 8901;
public static void main() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
System.out.println("S: Socket Established...");
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
ObjectOutputStream put = new ObjectOutputStream(
client.getOutputStream());
String s = "adios.wav";
String str = "C:/";
String path = str + s;
System.out.println("The requested file is path: " + path);
System.out.println("The requested file is : " + s);
File f = new File(path);
if (f.isFile()) {
FileInputStream fis = new FileInputStream(f);
byte[] buf = new byte[1024];
int read;
while ((read = fis.read(buf, 0, 1024)) != -1) {
put.write(buf, 0, read);
put.flush();
}
System.out.println("File transfered");
client.close();
serverSocket.close();
fis.close();
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
}
}
}
和客户;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket s = null;
BufferedInputStream get = null;
try {
s = new Socket("192.168.198.1", 8901);
get = new BufferedInputStream(s.getInputStream());
int u;
String str = "/mnt/sdcard/ad.wav";
FileOutputStream fs = new FileOutputStream(new File(str));
byte jj[] = new byte[1024];
while ((u = get.read(jj, 0, 1024)) != -1) {
fs.write(jj, 0, u);
}
fs.close();
System.out.println("File received");
s.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}