我正在编写一个文件传输客户端/服务器程序,其中服务器侦听客户端,客户端发送-l(目录中的文件列表)或-g(get file)命令。出于某种原因,在设置数据端口连接时,我不断收到“连接时出错:连接被拒绝”错误。在数据连接期间,Java客户端充当服务器并监听服务器通过目录列表或文件发送。并且服务器就像客户端一样,它启动数据连接。任何帮助表示赞赏。谢谢。
import java.io.*;
import java.net.*;
import java.lang.*;
public class Ftclient {
private Socket clientSocket;
private ServerSocket servSocket;
private Socket dataSocket;
PrintWriter out;
BufferedReader in;
BufferedReader stdIn;
BufferedReader dataIn;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
if (args.length < 4) {
System.err.println(
"Usage: java FtClient <host name> <port number> <command> <filename> <data_port>");
System.exit(1);
}
Ftclient one = new Ftclient();
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
String command = args[2];
int dataport = 0; boolean get = false;
one.initiateContact(hostName, portNumber);
if (command.equals("-g")){
get = true;
String filename = args[3];
dataport = Integer.parseInt(args[4]);
command = command.concat(" ");
command = command.concat(filename);
command = command.concat(" ");
command = command + dataport;
System.out.println("command: " + command);
}
else if (command.equals("-l")){
dataport = Integer.parseInt(args[3]);
command = command.concat(" ");
command = command + dataport;
System.out.println("command: " + command);
}
one.out.println(command);
String servResponse = one.in.readLine();
if (servResponse != null){
System.out.println(servResponse);
System.exit(0);
}
one.dataListen(hostName, dataport);
if (get){
one.getFile();
}
else {
one.getList();
}
one.dataSocket.close();
one.clientSocket.close();
}
void initiateContact (String name, int portNumber) throws IOException{
try {
clientSocket = new Socket(name, portNumber);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + name);}
}
void dataListen (String name, int dataNumber)throws IOException{
try {
servSocket = new ServerSocket(dataNumber);
dataSocket = servSocket.accept();
System.out.println("data connection set up and listening");
} catch (IOException e) {
System.err.println("Couldn't get the dataport set up");
}
}
void getList(){
System.out.println("no lists for now");
}
void getFile(){
System.out.println("no files for now");
}
}
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>
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);
int listenSocketFD, establishedConnectionFD, portNumber, charsRead, charsWritten, socketFD;
socklen_t sizeOfClientInfo;
char buffer[256];
struct sockaddr_in serverAddress, clientAddress;
struct hostent *serverHostInfo;
int main(int argc, char *argv[])
{
if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); }
// Set up the address struct for the server
memset((char *)&serverAddress, '\0', sizeof(serverAddress));
portNumber = atoi(argv[1]);
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, '\0', 256);
printf("connection set up and ready to receive\n");
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 %s\n", hostname);
dataport = atoi(strtok(NULL, "#"));
printf("datanum %d\n", dataport);
setupData(hostname, dataport);
}
else if (strcmp(token, "-g") ==0){
charsWritten = send(establishedConnectionFD, "file command", 13, 0);
if (charsRead < 0) error("ERROR writing to socket");
hostname = strtok(NULL, "#");
printf("hostname %s\n", hostname);
dataport = atoi(strtok(NULL, "#"));
printf("datanum %d\n", dataport);
filename = strtok(NULL, "#");
printf("file %s\n", filename);
setupData(hostname, dataport);
}
else {
// send invalid
charsWritten = send(establishedConnectionFD, "invalid command", 16, 0);
if (charsRead < 0) error("ERROR writing to socket");
}
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 now\n");
}
void setupData(char* hostname, int dataport){
// Set up the server address struct
memset((char*)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = dataport; // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.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 host\n"); exit(0); }
memcpy((char*)&serverAddress.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");
// Connect to server
if (connect(socketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to address
error("CLIENT: ERROR connecting");
// Get input message from user
printf("CLIENT: Enter text to send to the server, and then hit enter: ");
memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer array
fgets(buffer, sizeof(buffer) - 1, stdin); // Get input from the user, trunc to buffer - 1 chars, leaving \0
buffer[strcspn(buffer, "\n")] = '\0'; // Remove the trailing \n that fgets adds
// Send message to server
charsWritten = send(socketFD, buffer, strlen(buffer), 0); // Write to the server
if (charsWritten < 0) error("CLIENT: ERROR writing to socket");
if (charsWritten < strlen(buffer)) printf("CLIENT: WARNING: Not all data written to socket!\n");
// Get return message from server
memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer again for reuse
charsRead = recv(socketFD, buffer, sizeof(buffer) - 1, 0); // Read data from the socket, leaving \0 at end
if (charsRead < 0) error("CLIENT: ERROR reading from socket");
printf("CLIENT: I received this from the server: \"%s\"\n", buffer);
close(socketFD); // Close the socket
}