-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

ソケットは普遍的な概念であり、どの言語にも固有のものではありません。同じ C Ubuntu サーバー コードと C# Windows クライアント コードを使用できます。

あなたが世話をする必要があるいくつかのことは次のとおりです。

  • サーバーとクライアントをバインドする方法と使用するプロトコル。
  • ファイアウォールの設定。

これらの入力でキックスタートできることを願っています

ハッピーコーディング:)

于 2013-08-29T06:05:12.860 に答える