不同计算机 运行 不同语言的程序 运行 之间的基本通信

Basic Communicating Between Programs Running on Different Computers Running Different Languages

问题:对于初学者来说,获得两个程序的最快/最简单的方法是什么 运行ning 在不同的语言和 运行ning 在不同的计算机相互发送简单消息?

我的详细信息:我有两台计算机,一台 运行 运行 Visual C++ 程序,另一台 运行 运行 Visual Basic (两者都是 visual studio 2013 年的,尽管我可能需要使用一些较旧的 Visual Basic 代码(.NET 时代之前)来执行此操作)。由于硬件和遗留原因的结合,它们 运行 以不同的语言呈现。通信很简单:一个简单的二进制触发器(on/off 信号)就可以工作,或者如果简单的话,一个描述程序状态的字符、单词或字符串。

我尝试过的:我对通信协议之类的东西知之甚少,但我知道"Socket"编程可能是一种简单的方法这样的沟通。听起来 TCP 协议很适合我。不幸的是,我见过的所有示例都使用相同的编程语言进行通信(例如 C++ 到 C++ 或 basic 到 basic)。我也明白,替代方案可能是 运行 来自 C++ 的一些基本代码,反之亦然,但这似乎是一个有点麻烦的解决方案。

使用一些在线指南,当我的两台计算机都使用 C++(通过 Winsock 工具)时,我已经能够让它们相互通信,但是当我尝试将 C++ 服务器与 Visual基本客户端,他们无法连接。我正在使用的代码,大部分是从以下网站 (https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx) and (https://msdn.microsoft.com/en-us/library/windows/desktop/ms738545(v=vs.85).aspx) 被劫持和稍微修改的 在下面,如果你想看的话。

总结问题:

Visual Basic TCP 客户端:

Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports Microsoft.VisualBasic

Public Class GetSocket

Shared Sub Connect(server As [String], message As [String])
    Try
        ' Create a TcpClient. 
        ' Note, for this client to work you need to have a TcpServer  
        ' connected to the same address as specified by the server, port 
        ' combination. 
        Dim port As Int32 = 27015
        Dim client As New TcpClient(server, port)

        ' Translate the passed message into ASCII and store it as a Byte array. 
        Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)

        ' Get a client stream for reading and writing. 
        '  Stream stream = client.GetStream(); 
        Dim stream As NetworkStream = client.GetStream()

        ' Send the message to the connected TcpServer. 
        stream.Write(data, 0, data.Length)

        Console.WriteLine("Sent: {0}", message)

        ' Receive the TcpServer.response. 
        ' Buffer to store the response bytes.
        data = New [Byte](256) {}

        ' String to store the response ASCII representation. 
        Dim responseData As [String] = [String].Empty

        ' Read the first batch of the TcpServer response bytes. 
        Dim bytes As Int32 = stream.Read(data, 0, data.Length)
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
        Console.WriteLine("Received: {0}", responseData)

        ' Close everything.
        stream.Close()
        client.Close()
    Catch e As ArgumentNullException
        Console.WriteLine("ArgumentNullException: {0}", e)
    Catch e As SocketException
        Console.WriteLine("SocketException: {0}", e)
    End Try

    Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
    Console.Read()
End Sub 'Connect

Public Shared Sub Main()
    Dim host As String = "192.168.107.254"
    Dim message As String = "I SPEAK TO YOU FROM THE OTHER SIDE"

    Connect(host, message)

End Sub 'Main
' WHY ARE COMMENTS SO WEIRD IN BASIC
End Class

Visual C++ 服务器:

#include "stdafx.h"

#include <winsock2.h>

#include <ws2tcpip.h>

#include <stdio.h>




#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_PORT "27015"

#define DEFAULT_BUFLEN 512




int main() {

WSADATA wsaData;

int iResult;




// Initialize Winsock

iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (iResult != 0) {

    printf("WSAStartup failed: %d\n", iResult);

    getchar();

    return 1;

}




struct addrinfo *result = NULL, *ptr = NULL, hints;




ZeroMemory(&hints, sizeof(hints));

hints.ai_family = AF_INET;

hints.ai_socktype = SOCK_STREAM;

hints.ai_protocol = IPPROTO_TCP;

hints.ai_flags = AI_PASSIVE;




// Resolve the local address and port to be used by the server

iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);



if (iResult != 0) {

    printf("getaddrinfo failed: %d\n", iResult);

    WSACleanup();

    getchar();

    return 1;

}




SOCKET ListenSocket = INVALID_SOCKET;




ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);



if (ListenSocket == INVALID_SOCKET) {

    printf("Error at socket(): %ld\n", WSAGetLastError());

    freeaddrinfo(result);

    WSACleanup();

    getchar();

    return 1;

}




// Setup the TCP listening socket

iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);

if (iResult == SOCKET_ERROR) {

    printf("bind failed with error: %d\n", WSAGetLastError());

    freeaddrinfo(result);

    closesocket(ListenSocket);

    WSACleanup();

    getchar();

    return 1;

}




freeaddrinfo(result);




if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {

    printf("Listen failed with error: %ld\n", WSAGetLastError());

    closesocket(ListenSocket);

    WSACleanup();

    return 1;

}




SOCKET ClientSocket;




ClientSocket = INVALID_SOCKET;




// Accept a client socket

ClientSocket = accept(ListenSocket, NULL, NULL);

if (ClientSocket == INVALID_SOCKET) {

    printf("accept failed: %d\n", WSAGetLastError());

    closesocket(ListenSocket);

    WSACleanup();

    return 1;

}




char recvbuf[DEFAULT_BUFLEN];

int iSendResult;

int recvbuflen = DEFAULT_BUFLEN;




// Receive until the peer shuts down the connection

do {

    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);

    if (iResult > 0) {

        printf("Bytes received: %d\n", iResult);

        printf("recieved message: %s\n", recvbuf);

        // Echo the buffer back to the sender

        iSendResult = send(ClientSocket, recvbuf, iResult, 0);

        if (iSendResult == SOCKET_ERROR) {

            printf("send failed: %d\n", WSAGetLastError());

            closesocket(ClientSocket);

            WSACleanup();

            return 1;

        }

        printf("Bytes sent: %d\n", iSendResult);

    }

    else if (iResult == 0)

        printf("Connection closing...\n");

    else {

        printf("recv failed: %d\n", WSAGetLastError());

        closesocket(ClientSocket);

        WSACleanup();

        return 1;

    }




} while (iResult > 0);




// shutdown the send half of the connection since no more data will be sent

iResult = shutdown(ClientSocket, SD_SEND);

if (iResult == SOCKET_ERROR) {

    printf("shutdown failed: %d\n", WSAGetLastError());

    closesocket(ClientSocket);

    WSACleanup();

    return 1;

}




// cleanup

closesocket(ClientSocket);

WSACleanup();




printf("Success!");

getchar();

return 0;

}

is a direct socket communication between Visual C++ and Visual Basic Possible?

是的。

Are there better alternatives?

可能,取决于...

Am I an idiot?

目前未知。你也在PHP/jQuery编程吗?

Is there somewhere a beginner should go to learn about these types of things?
Let me know if there is anything I can do to clarify the question.

SO 上有大量关于套接字编程的问答 :)