我正在尝试将一些文件从我的Android应用程序传输到服务器。服务器端编码在C language
中。我在我的应用程序中实现了一个服务,它接受文件路径并通过OutputStream
结束文件。但我无法实现服务器端代码来接受传入的文件。这是我的代码:
客户端(Android应用)
public class Servic extends Service
{
private boolean isRunning = false;
private static final String SERVER_IP = "192.168.43.112";
private static final int SERVERPORT = 6000;
private Socket socket;
Thread ClientThread = null;
String st = null;
String path = null;
public void onCreate()
{
}
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
path=(String) intent.getExtras().get("path");
isRunning = true;
this.ClientThread = new Thread(new ClientThread());
this.ClientThread.start();
return START_STICKY;
}
public void onDestroy()
{
super.onDestroy();
isRunning = false;
}
public class ClientThread implements Runnable
{
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr,SERVERPORT);
File file = new File(path);
byte[] bytes = new byte[8192];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream out = socket.getOutputStream();
out.write((int)file.length());
int count,file_size;
while ((count = bis.read(bytes)) > 0) {
System.out.println(count);
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
}
}
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
服务器端(C语言)
int main(int argc, char *argv[])
{
WSADATA wsa;
socklen_t addrlen;
SOCKET s , new_socket;
char buffer[256];
struct sockaddr_in server , client;
int c,n;
int result;
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("ERROR initlizaing winsock2 dll : %d",WSAGetLastError());
return 1; // exit program with error.
}
printf("Initialised.\n");
s = socket(AF_INET,SOCK_STREAM, 0);
if(s == INVALID_SOCKET)
{
printf("error at creating socket :%d" ,WSAGetLastError());
WSACleanup();
return 1;
}
printf("socket created\n");
memset(&server, 0, sizeof server);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(6000);
if (bind(s , (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind fialed with errror code : %d",WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
listen(s , 3);
printf("waiting for incoming connections\n");
c = sizeof(struct sockaddr_in);
new_socket = accept(s , (struct sockaddr *)&client,&c);
if(new_socket == INVALID_SOCKET)
{
printf("accept fialed with error code : %d" ,WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
printf("Connection acceptëd");
//as per my knowledge, file accepting code should be somewhere here.
getchar();
closesocket(s);
WSACleanup();
return 0;
}
如果你能在这里帮助我,那会很有帮助。
答案 0 :(得分:1)
检查是否有效。编写此代码是为了将文件发送到客户端 服务器:https://github.com/dinanjana/CO323/blob/master/SocketProgrammingWithC/Lab03/TCPServer.c 客户: https://github.com/dinanjana/CO323/blob/master/SocketProgrammingWithC/Lab03/TCPClient.c 正如@ja_mesa所提到的,你需要调用recv函数来获取消息