C服务器不会接受任何客户端

时间:2012-12-04 03:41:54

标签: c networking

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


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

  

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

以下是客户端的输出:

  

启动新的客户端连接....   港口:8081
  地址:127.0.0.1
  成功?假
  连接失败,请尝试重新启动服务器。


这是我的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();
    }
}

来自telnet:

  

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


来自java的

异常:

  

java.net.ConnectException:拒绝连接

3 个答案:

答案 0 :(得分:2)

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

您的服务器设置在返回时被取消 来自setupServer()的call-by-value语义。

答案 1 :(得分:1)

您在server.c中的功能(setupServerstartServer)应该struct sockaddr_in *或不将其作为参数并引用全局serverSettings

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

答案 2 :(得分: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);