我想为我的英语道歉。这不是我的母语。
我正在尝试编写简单的TCP服务器和客户端。从客户端向服务器发送号码时遇到问题。 以下是客户端的代码:
public class ConnectionHandler {
private InetAddress address;
private int port;
private Socket socket;
private DataOutputStream dos;
private DataInputStream dis;
public ConnectionHandler(String ipAddress, String port) {
try {
address = InetAddress.getByName(ipAddress);
this.port = Integer.parseInt(port);
connectionHandle();
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectionHandle() {
try {
socket = new Socket(address, port);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
getCatalogueList();
} catch (Exception e) {
e.printStackTrace();
}
private void getCatalogueList() {
try {
dos.writeInt(1);
sendFile();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile() {
try{
dos.writeInt(2);
} catch(Exception e) {
e.printStackTrace();
}
}
当我在getCatalogueList()中发送数字1时,一切正常,但是在sendFile中我正在尝试发送数字2,但我的服务器正在变为0.我已检查过如果我在发送数字一个功能:
private void getCatalogueList() {
dos.writeInt(1);
dos.writeInt(2);
}
一切正常。只有当我使用两种不同的功能时才会出现问题。
如果有人可以帮助我如何防止这种情况并向我解释为什么会发生这种情况,我将非常感激。
服务器代码(它在C中,我使用的是bsd套接字)
int handleConnection(int clientSocket) {
short connectionClosed = False;
long action;
while(!connectionClosed) {
recv(clientSocket, &action, sizeof(int), 0);
action = ntohl(action);
printf("%i\n", action);
}
return 0;
}
int main() {
const int port = 8080;
const int maxConnection = 20;
int listeningSocket, clientSocket;
struct sockaddr_in server, client;
struct hostent *host;
socklen_t sin_size = sizeof(struct sockaddr_in);
char myhostname[1024];
listeningSocket = socket(PF_INET, SOCK_STREAM, 0);
gethostname(myhostname, 1023);
host = gethostbyname(myhostname);
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *(struct in_addr*) host->h_addr;
if (bind(listeningSocket, (struct sockaddr*) &server, sizeof(struct sockaddr)) == -1) {
return -1;
}
listen(listeningSocket, maxConnection);
while(True) {
sin_size = sizeof(struct sockaddr_in);
clientSocket = accept(listeningSocket, (struct sockaddr*) &client, &sin_size);
if(fork() == 0) {
handleConnection(clientSocket);
close(clientSocket);
exit(0);
}
else {
printf("Waiting for connection.\n");
continue;
}
}
return 0;
}
答案 0 :(得分:1)
您忽略了recv().
返回的计数。它可能是-1,表示错误页面,或者为0,表示流的结束,或1和sizeof int
之间的任何正值。相反,你假设它填充缓冲区。
它与DataOutputStream.
您还在父进程中泄漏客户端套接字,而不是检查socket()
或accept()
或listen().