我的FTP程序一直给出一个断管错误,我已经经历了常见的原因,但仍然无法弄清楚。尝试引入一些睡眠时间,但这导致了更多问题。下面是我的客户端和服务器代码。任何帮助,不胜感激。最初错误不是每次运行都会发生,但现在发生了。谢谢。
ftserver.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issues
void startControl(int portNo);
void setupData(char* hostname, int dataport, char* command, char* filename);
void sendDirectory();
void sendFile(char*filename);
int listenSocketFD, establishedConnectionFD, portNumber, charsRead, charsWritten, socketFD;
socklen_t sizeOfClientInfo;
char buffer[256];
struct sockaddr_in serverAddress, clientAddress, javaAddress;
struct hostent *serverHostInfo;
int main(int argc, char *argv[])
{
if (argc < 2) { fprintf(stderr,"USAGE: %s portn", argv[0]); exit(1); }
// Set up the address struct for the server
memset((char *)&serverAddress, ' ', sizeof(serverAddress));
portNumber = atoi(argv[1]);
//signal(SIGPIPE,SIG_IGN);
startControl(portNumber);
while (1){
// Accept a connection, blocking if one is not available until one connects
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect
establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo);
if (establishedConnectionFD < 0) error("ERROR on accept");
// Get the message from the client and display it
memset(buffer, ' ', 256);
printf("connection set up and ready to receiven");
charsRead = recv(establishedConnectionFD, buffer, 255, 0); // Read the client's message from the socket
if (charsRead < 0) error("ERROR reading from socket");
printf("SERVER: I received this from the client: "%s"n", buffer);
char *token; int dataport; char* filename; char* hostname;
token = strtok(buffer, "#");
if (strcmp(token, "-l") == 0){
charsWritten = send(establishedConnectionFD, "list command", 13, 0);
if (charsRead < 0) error("ERROR writing to socket");
hostname = strtok(NULL, "#");
printf("hostname %sn", hostname);
dataport = atoi(strtok(NULL, "#"));
printf("datanum %dn", dataport);
// close(establishedConnectionFD);
filename = "";
setupData(hostname, dataport, token, filename);
}
else {
// send invalid
charsWritten = send(establishedConnectionFD, "invalid command", 16, 0);
if (charsRead < 0) error("ERROR writing to socket");
// close(establishedConnectionFD);
}
close(establishedConnectionFD); // Close the existing socket which is connected to the client
}
close(listenSocketFD); // Close the listening socket
return 0;
}
void startControl(int portNo){
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) error("ERROR opening socket");
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(portNo);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// Enable the socket to begin listening
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port
error("ERROR on binding");
listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections
printf("returning from startcontol right nown");
}
void setupData(char* hostname, int dataport, char* command, char* filename){
// Set up the server address struct
memset((char*)&serverAddress, ' ', sizeof(serverAddress)); // Clear out the address struct
portNumber = dataport; // Get the port number, convert to an integer from a string
javaAddress.sin_family = AF_INET; // Create a network-capable socket
javaAddress.sin_port = htons(portNumber); // Store the port number
serverHostInfo = gethostbyname(hostname); // Convert the machine name into a special form of address
if (serverHostInfo == NULL) { fprintf(stderr, "CLIENT: ERROR, no such hostn"); exit(0); }
memcpy((char*)&javaAddress.sin_addr.s_addr, (char*)serverHostInfo->h_addr, serverHostInfo->h_length);
// Set up the socket
socketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (socketFD < 0) error("CLIENT: ERROR opening socket");
int connectionAttempts = 0; int status = 0;
do {
connectionAttempts++;
status = connect(socketFD, (struct sockaddr *) &javaAddress, sizeof(javaAddress));
} while (status == -1 && connectionAttempts < 10);
//sleep(100);
if (strcmp(command, "-l") == 0){
sendDirectory();
printf("sendDir successn");
}
close(socketFD); // Close the socket
}
void sendDirectory(){
printf("in send directoryn");
char fileList[1000];
memset(fileList, ' ', sizeof(fileList));
DIR *dir = opendir(".");
if (dir == NULL){
perror("could not open directory");
exit(1);
}
struct dirent *ent; struct stat info;
int numFiles = 0;
while((ent = readdir(dir)) != NULL) {
//printf("in send directory whilen");
//printf("filename%sn", ent->d_name);
stat(ent->d_name, &info);
//skip over directories
if (S_ISDIR(info.st_mode)){
continue;
}
else if ((strcmp(ent->d_name, ".") == 0) && (strcmp(ent->d_name, "..") == 0)){
continue;
}
else {
printf("filename%sn", ent->d_name);
//keep adding the filenames to the filelist
strcat(fileList, ent->d_name);
strcat(fileList, ",");
numFiles++;
}
}
printf("fileList %sn", fileList);
printf("length %dn", strlen(fileList));
charsWritten = send(socketFD, fileList, strlen(fileList), 0);
printf("charsWritten successn");
//closedir(dir);
}
FTCLIENT.java
package ftclient;
public class Ftclientmini {
private Socket echoSocket;
private ServerSocket servSocket;
private Socket dataSocket;
PrintWriter out;
BufferedReader in;
PrintWriter dataOut;
BufferedReader dataIn;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
String filename = ""; int datanum = 0;
String command = args[2];
if (command.equals("-l")){
if (args.length != 4)
System.err.println("Usage: java EchoClient <host name> "
+ "<port number> <command> <dataport>");
datanum = Integer.parseInt(args[3]);
}
Ftclientmini one = new Ftclientmini();
one.startControl(hostName, portNumber);
System.out.println("have set up the control connectionn");
one.sendCommand(command, filename, hostName, datanum);
String servResponse = one.in.readLine();
if (servResponse != null){
System.out.println(servResponse);
if (servResponse.equals("invalid command"))
System.exit(0);
else{
//byte[] myarray = new byte[1024];
String bytesRead; String[] retVal;
one.startData(datanum);
if (command.equals("-l")){
while ((bytesRead = one.dataIn.readLine()) != null){
//bytesRead = one.dataIn.readLine();
retVal = bytesRead.split(",");
for (String temp: retVal){
System.out.println(temp);
}
}
}
}
}
one.servSocket.close();
one.dataSocket.close();
one.echoSocket.close();
System.exit(0);
}
void startControl(String name, int number){
try {
echoSocket = new Socket(name, number);
out = new PrintWriter(
echoSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
catch (IOException e)
{
System.err.println("Couldn't get IO for connection to" + name);
e.printStackTrace();
}
}
void sendCommand(String command, String filename, String host, int datanum){
String stringData = Integer.toString(datanum);
if (command.equals("-l")){
command = command.concat("#" + host + "#" + stringData +"#");
System.out.println("sending: " + command);
out.println(command);
}
else {
command = command.concat("#" + host + "#" + stringData + "#" + filename + "#");
System.out.println("sending: " + command);
out.println(command);
}
System.out.println("finished sending command");
}
void startData(int datanum){
try {
servSocket = new ServerSocket(datanum);
//servSocket.setSoTimeout(10000);
System.out.println("wait for a client");
dataSocket = servSocket.accept();
System.out.println("ftclient.java has been accepted");
dataOut = new PrintWriter(
dataSocket.getOutputStream(), true);
dataIn = new BufferedReader(
new InputStreamReader(dataSocket.getInputStream()));
}
catch (IOException e)
{
System.err.println("Couldn't get IO for connection");
e.printStackTrace();
}
}
}
int offset = 0;
while (!feof(fp)){
readBytes = fread(fileBuffer, 1, sizeof(fileBuffer), fp);
似乎将偏移量重置为零想要在"while"循环内...?
我假设你的意思是你的服务器正在接收SIGPIPE。 那时客户是否还活着?