-1

在这里我想问一下如何通过套接字编程在客户端(在Windows上,使用C#.NET)和服务器(在Ubuntu上,使用C)之间创建通信。如果服务器客户端都是 C#.NET 或 C 但不知道按照我的要求去做,我已经成功完成了。我试图在几个站​​点中查找信息,但找不到确切的站点。我感谢任何评论。谢谢你。

这是客户端上的简单代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        // Receiving byte array  
        byte[] bytes = new byte[1024];
        Socket senderSock;

        public Form1()
        {
            InitializeComponent();

        }



        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            try
            {
                // Create one SocketPermission for socket access restrictions 
                    SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission 
                    TransportType.Tcp,        // Defines transport types 
                    "",                       // Gets the IP addresses 
                    SocketPermission.AllPorts // All ports 
                    );

                // Ensures the code to have permission to access a Socket 
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance            
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost 
                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint 
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);

                // Create one Socket object to setup Tcp connection 
                senderSock = new Socket(
                    ipAddr.AddressFamily,// Specifies the addressing scheme 
                    SocketType.Stream,   // The type of socket  
                    ProtocolType.Tcp     // Specifies the protocols  
                    );

                senderSock.NoDelay = false;   // Using the Nagle algorithm 

                // Establishes a connection to a remote host 
                senderSock.Connect(ipEndPoint);



            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                // Sending message 
                //<Client Quit> is the sign for end of data 
                string theMessageToSend = text_IP.Text;
                byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "<Client Quit>");

                // Sends data to a connected Socket. 
                int bytesSend = senderSock.Send(msg);


            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }



    }
}

这是服务器中的代码(在 C 中)

include "stdio.h"
#include "stdlib.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "error.h"
#include "strings.h"
#include "unistd.h"
#include "arpa/inet.h"

#define ERROR    -1
#define MAX_CLIENTS    
#define MAX_DATA    1024


main(int argc, char **argv)
{
    struct sockaddr_in server;
    struct sockaddr_in client;
    int sock;
    int new,i;
    int sockaddr_len = sizeof(struct sockaddr_in);
    printf("sockaddr_len");
    int data_len;
    char data[MAX_DATA];
    char temp[MAX_DATA];


    if((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
    {
        perror("server socket: ");
        exit(-1);
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[1]));
    server.sin_addr.s_addr = INADDR_ANY;
    bzero(&server.sin_zero, 8);

    if((bind(sock, (struct sockaddr *)&server, sockaddr_len)) == ERROR)
    {
        perror("bind : ");
        exit(-1);
    }

    if((listen(sock, MAX_CLIENTS)) == ERROR)
    {
        perror("listen");
        exit(-1);
    }
    printf("\nThe TCPServer Waiting for client on port %d\n",ntohs(server.sin_port));
        fflush(stdout);

    while(1) // Better signal handling required
    {
        if((new = accept(sock, (struct sockaddr *)&client, &sockaddr_len)) == ERROR)
        {
            perror("accept");
            exit(-1);
        }

        printf("New Client connected from port no %d and IP %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));

        data_len = 1;


        while(data_len)
        {
            data_len = recv(new, data, MAX_DATA, 0);
            printf("\nRecieved mesg from client: %s", data);

            for( i = 0; data[ i ]; i++)
            {
                /* if(data[i]=='a' || data[i]=='e' || data[i]=='i' ||data[i]=='o' || data[i]=='u' )
                    data[ i ] = toupper( data[ i ] );
                else */
                data[ i ] = data[ i ] ;

            }    

            if(data_len)
            {

                send(new, data, data_len, 0);
                data[data_len] = '\0';
                printf("\nSent mesg to client: %s", data);
            }

        }

        printf("Client disconnected\n");

        close(new);

    }

    close(sock);


}
4

3 回答 3

0

在您的客户代码中,您GetHostEntry使用空主机名调用。这将为您提供客户端的 IP 地址。

您应该GetHostEntry使用服务器的主机名调用:

// Resolves a host name to an IPHostEntry instance            
IPHostEntry ipHost = Dns.GetHostEntry("Server.Host.Name");

// Gets first IP address associated with a localhost 
IPAddress ipAddr = ipHost.AddressList[0];

// Creates a network endpoint 
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510); 
于 2013-09-02T08:31:36.540 回答
0

所以我假设你的客户至少可以互相交谈。但看起来您的问题是您从 C# 发送 Unicode 格式的文本,然后在客户端将其作为 ASCII 接收。除非您的“C”客户端的默认值不是 ASCII。

于 2013-08-29T06:08:33.797 回答
0

套接字是通用概念,并不特定于任何语言。您可以继续使用相同的 C Ubuntu 服务器代码和 C# Windows 客户端代码。

您需要注意的几件事是:

  • 您如何绑定服务器和客户端以及使用的协议。
  • 防火墙设置。

希望您可以从这些输入开始

快乐编码:)

于 2013-08-29T06:05:12.860 回答