0

这是我的问题:当我启动服务器并尝试使用客户端连接到它时,客户端找不到端点。我几乎可以肯定它不是客户端,因为我可以使用相同的客户端连接到另一台服务器。是的,我为客户端和服务器使用相同的端口号,是的,我使用“127.0.0.1”作为地址。我可以在同一个端口上启动不同的服务器并使用客户端连接到它。我的客户代码贴在最底部。当我运行我的服务器时,它位于它假设的位置,在 socket = acceptSocket(...) 行上,但我的客户端无法连接到它。有没有人看到问题?谢谢阅读!


这是我为服务器获得的输出:

创建新服务器...
等待客户端...

这是客户端的输出:

启动一个新的客户端连接....
PORT: 8081
ADDRESS: 127.0.0.1
成功了吗?false
连接失败,请尝试重新启动服务器。


这是我的 server.c 代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "server.h"

//returns a setup server socket
int setupServer(int port, struct sockaddr_in serv)
{
    memset(&serv, 0, sizeof(serv));    /* zero the struct before filling the fields */
    serv.sin_family = AF_INET;         /* set the type of connection to TCP/IP */
    serv.sin_addr.s_addr = INADDR_ANY; /* set our address to any interface */
    serv.sin_port = htons(port);    /* set the server port number */ 

    return socket(AF_INET, SOCK_STREAM, 0); // returns a setup server socket
}

int startServer(int serverSocket, struct sockaddr_in serv)
{
    bind(serverSocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
    return listen(serverSocket, 1);
}

int acceptSocket(int serverSocket, struct sockaddr_in serv, struct sockaddr_in client)
{
    unsigned int socksize = sizeof(struct sockaddr_in); // how many memory blocks is socket
    printf("%s %d","Socket sze:::", socksize);
    return accept(serverSocket, (struct sockaddr *)&client, &socksize);
}

void closeServer(int socket)
{
    shutdown(socket, SHUT_RDWR);
    close(socket);
}

这是 server.c (server.h) 的标头:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#ifndef ServerTools_server_h
#define ServerTools_server_h

int setupServer(int port, struct sockaddr_in serv);
int startServer(int serverSocket, struct sockaddr_in serv);
int acceptSocket(int serverSocket, struct sockaddr_in serv, struct sockaddr_in client);
void closeServer(int socket);

#endif

这是我用来创建服务器并启动它的 main.c:

#include <stdio.h>
#include "server.h"

#define PORT 8081

void println(char* c);
int serverSocket;

struct sockaddr_in serverSettings;

int main(int argc, const char * argv[])
{
    println("Creating a new server...");
    serverSocket = setupServer(PORT, serverSettings);

    startServer(serverSocket, serverSettings);

    println("waiting for a client...");

    struct sockaddr_in client;
    int socket = acceptSocket(serverSocket, serverSettings, client);

    printf("%s %d", "socket accepted: ", socket);

    return 0;
}

void println(char* c)
{
    printf("%s%s", c, "\n");
}

我的客户端代码,用 Java 编写:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client implements Runnable
{
    public Client()
    {
        System.out.println("Starting up a new client connection....");
        System.out.println("PORT: " + PORT);
        System.out.println("ADDRESS: " + ADDRESS);
        boolean success = connect();
        System.out.println("Success? " + success);
        if(!success)
        {
            System.out.println("Connect failed, try restarting server.");
            System.exit(0);
        }

        System.out.println("Connection is setup, listening for data...");

        running = true;
        inputThread = new Thread(this);
        inputThread.start();

        consoleThread = new Thread(new Runnable()
        {
            public void run()
            {
                consoleInput = new BufferedReader(new InputStreamReader(System.in));

                while(running)
                {
                    try
                    {
                        String message = "";
                        while((message = consoleInput.readLine()) != null)
                        {
                            Client.this.sendMessage(message);
                        }
                    }catch(Exception e){}
                }
            }
        });
        consoleThread.start();

    }

    public boolean connect()
    {
        try
        {
            socket = new Socket(ADDRESS, PORT);
            writer = new PrintWriter(socket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            return true;
        }catch(Exception e){}
        return false;
    }

    public void run()
    {
        while(running)
        {
            try
            {
                String message = "";
                while((message = reader.readLine()) != null)
                {
                    System.out.println("Message recieved: " + message);
                }
            }catch(Exception e){}
        }
    }

    public void sendMessage(String message)
    {
        writer.println(message);
        writer.flush();
        if(!writer.checkError())
            System.out.println("Message sent: " + message);
        else
            System.out.println("Message not sent.");
    }

    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;
    private BufferedReader consoleInput;
    private boolean running;

    private Thread consoleThread;
    private Thread inputThread;

    public static final int PORT = 8081;
    public static final String ADDRESS = "127.0.0.1";

    public static void main(String args[])
    {
        new Client();
    }
}

从远程登录:

正在尝试 127.0.0.1...
telnet:连接到地址 127.0.0.1:连接被拒绝
telnet:无法连接到远程主机


来自java的异常:

java.net.ConnectException:连接被拒绝

4

3 回答 3

2

尝试将 serverSettings 的指针发送到 setupServer() 和 startServer()。

您的服务器设置在从 setupServer() 返回时被取消以获取按值调用语义。

于 2012-12-04T03:57:54.483 回答
1

您在 server.c( setupServer, startServer) 中的函数应将struct sockaddr_in *其作为参数或不将其作为参数并引用 global serverSettings

您的代码的问题是,当您将参数作为struct sockaddr_in serv并更新它时,更改不会反映在传递的结构变量中。

于 2012-12-04T03:58:07.603 回答
1

您正在丢失传递给 的值serv,因为在 的上下文中,setupServer()您有 的值的本地副本,serverSettings并且您的修改在函数之外不可见。要在完成后保留它们setupServer,您需要使用指针:

int setupServer(int port, struct sockaddr_in *serv)
{
    memset(serv, 0, sizeof(*serv));    /* zero the struct before filling the fields */
    serv->sin_family = AF_INET;         /* set the type of connection to TCP/IP */
    serv->sin_addr.s_addr = INADDR_ANY; /* set our address to any interface */
    serv->sin_port = htons(port);    /* set the server port number */ 

    return socket(AF_INET, SOCK_STREAM, 0); // returns a setup server socket
}

然后按如下方式调用它:

serverSocket = setupServer(PORT, &serverSettings);
于 2012-12-04T03:59:14.543 回答