我使用套接字开发了一个基本的Java客户端/服务器。使用PrintWriter
,一切都按预期工作。但是,如果我将服务器输出方法更改为DataOutputStream
,则客户端上的InputStream
长度为0,最终会超时。
服务器端
当我使用(1)时它起作用:
bufferOut = new PrintWriter(new BufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);
bufferOut.println(response);
但不是在我使用(2)的时候:
bufferOut = new DataOutputStream(socket.getOutputStream());
bufferOut.write(response.getBytes("US-ASCII"));
客户的长度为InputStream
= 0
遇到的唯一异常是当客户端超时并关闭套接字时 - 服务器然后抛出一个损坏的管道异常。
客户端
DataInputStream in = new DataInputStream(socket.getInputStream());
String read = bufferIn.readLine();
我不理解什么?有什么遗失的吗?我还能提供什么帮助?
修改
更新了客户端:
DataInputStream dis = new DataInputStream(socket.getInputStream());
int length = dis.available();
// create buffer
byte[] buf = new byte[length];
// read the full data into the buffer
dis.readFully(buf);
Log.d(TAG, "buffer length: "+buf.length);
// for each byte in the buffer
for (byte b:buf){
// convert byte to char
char c = (char)b;
// append
message_string += c;
}
仍然没有用(2) - logcat buf.length = 0
获取数据答案 0 :(得分:0)
void Fill_Users_db(Users** users_db, Quantity* qnty)
{
//fills the employee database array according to the file
int num_of_users = 0, i;
FILE *file = fopen("Users.txt", "r"); //open the file
if (!file) //if failed to open file
{
printf("Error opening file!\n");
return;
}
fscanf(file, "%d", &qnty->Users);
*users_db = (Users*)calloc(qnty->Users, sizeof(Users)); //allocate memory and nullify elements //used calloc coz it takes 2 arguments and not 1 as calloc.
if (!*users_db)
{
printf("Memory allocation failed!\n");
return;
}
//for each user get data from the file and allocate memory to the relevant struct variables
for (i = 0; !feof(file); i++)
{
fscanf(file, "%s" "%s" "%s" "%s" "%s" "%s", &(*users_db)[i].userType, &(*users_db)[i].userName, &(*users_db)[i].password, &(*users_db)[i].id, &(*users_db)[i].firstName, &(*users_db)[i].lastName);
fgetline(&(*users_db)[i].address, file);
}
fclose(file); //close the file
}
附加一个行终止符。 println()
没有。 write()
阻塞,直到读取行终止符,或者发生EOS或异常。
如果您在一端使用readLine()
,则应该使用readLine()
,另一端使用BufferedInputStream.readLine(),
,而不是Writer