我正在开发一个小项目来确定网络的上传速度。我在C中创建了一个小型服务器,它根据客户端发送的1 MB数据计算上传速度。
这是C中的服务器代码:
void main(int argc, char** argv){
int sock_desc = 0;
int connfd = 0;
int read_size = 0;
int clntSock;
struct sockaddr_in serv_addr;
struct sockaddr_in echoClntAddr;
int rc;
char client_message[1048576];//1048576 //524288
time_t start,end;
double t;
int temp;
double Bandwidth;
int result[1];
struct timeval tv1, tv2;
sock_desc = socket(AF_INET, SOCK_STREAM, 0);
if(sock_desc < 0 )
dieWithError("Unable to open Socket\n");
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET ;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(7024);
if(bind(sock_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
dieWithError("bind failed\n");
if(listen(sock_desc,MAX_CONNECTIONS) < 0)
dieWithError("listen failed\n");
clntSock = sizeof(struct sockaddr);
bahar:
connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr,(socklen_t*)&clntSock);
printf("Connection accepted\n");
while(1){
read_size = recv(connfd , client_message ,1, 0);
gettimeofday(&tv1, NULL);
if(read_size < 1048576)
read_again: temp = read_size;
read_size = 0;
read_size = recv(connfd , client_message+temp , (sizeof(client_message)-temp), 0);
read_size+=temp;
printf("read size is %d\n",read_size);
temp=0;
if(read_size < 1048576)//524288
goto read_again;
gettimeofday(&tv2, NULL);
t = (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec);
read_size*=8;
read_size/=1024;
Bandwidth = read_size/t;
result[0]= (int) Bandwidth;
// Bandwidth/=1024;
printf("Network Bandwidth is %d Kbps\n",result[0]);//Bandwidth);
rc = send(connfd , result , 4, 0);//send Bandwidth to client
goto bahar;
}
}
void dieWithError(char *errormsg){
printf("%s", errormsg);
}
这是我在Java中的客户端代码:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class JavaSAmpleClient {
public static void main(String[] args)throws IOException {
int i;
int arr[] = new int[10];
byte bfr[] = new byte[1024*1024];
for (i=0;i<1048576;i++)
bfr[i] = (byte)i;
Socket s1 = new Socket("127.0.0.1",7024);
BufferedOutputStream bos = new BufferedOutputStream(s1.getOutputStream());
BufferedInputStream bos1 = new BufferedInputStream(s1.getInputStream());
bos.write(bfr);
i= bos1.read();//read bandwidth returned by server
System.out.println(i);
}
}
面临的问题是,如果我用C编写客户端程序,它就能够正确地接收上传速度。但是在Java的情况下我没有得到正确的结果。
对于Eg: 对于java客户端: 如果服务器将带宽发送为4282279,则Java客户端将其作为167接收。
如果是C客户端: 如果服务器将带宽发送为4282279,则客户端将其作为4282279接收。
我无法在C中进行客户端编程,因为我需要在android上运行客户端应用程序。
答案 0 :(得分:0)
您的C发送代码中存在字节顺序问题,Java代码中存在read()
编码问题。
result[0] = htonl(Bandwidth);
。DataInputStream
周围换BufferedInputStream
,然后致电readInt()
。