C#套接字编程:如何通过名称而不是IP来识别客户端

时间:2017-06-18 22:06:02

标签: c# sockets

我是socket编程的新手。我正在开发一个客户端 - 服务器通信程序,当客户端连接到服务器时,很难显示客户端名称而不是IP地址。有谁能建议我一个好方法?我怎么能这样做?我还需要知识产权以进行进一步的沟通。 这是我的客户端代码:

mTcpClient = new TcpClient();
mTcpClient.BeginConnect(ipa, nPort, onCompleteConnect, mTcpClient);

那个onCompleteConnect函数:

void onCompleteConnect(IAsyncResult iar)
    {

        TcpClient tcpc;

        try
        {
            tcpc = (TcpClient)iar.AsyncState;
            tcpc.EndConnect(iar);
            mRx = new byte[512];
            tcpc.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromServerStream, tcpc);

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

现在,我想发送客户端名称并在服务器端接收。我该怎么办?

2 个答案:

答案 0 :(得分:2)

Environment.UserName属性从客户端发送到服务器。

答案 1 :(得分:1)

使用var https = require('https') var url = 'https://opentdb.com/api.php?amount=1&category=15&type=multiple'; https.get(url, function(res){ var body = ''; res.on('data', function(chunk){ body += chunk; }); res.on('end', function(){ var trivapi = JSON.parse(body); console.log("Got a response: ", trivapi.results[0].question); }); }).on('error', function(e){ console.log("Got an error: ", e); }); StreamWriter阅读字符串。

示例

客户端:

StreamReader

服务器:

StreamWriter sW = new StreamWriter(mTcpClient.GetStream());
sW.AutoFlush = true;

// Send the username
sW.WriteLine(Environment.UserName);