如何为多个客户端制作简单的Socket Server? [英] How to make simple Socket Server for multiple clients?

查看:126
本文介绍了如何为多个客户端制作简单的Socket Server?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这个:

服务器:

 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
IPAddress ipAddress = ipHostInfo.AddressList [ 0 ];
for int i = 0 ; i < max_clients; i ++)
{
endpoint [i] = new IPEndPoint(ipAddress,port_starting + i);
listener [i] = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
listener [i] .Bind(endpoint [i]);
listener [i] .Listen( 100 );
}

while true ){
for int i = 0 ; i < max_clients; i ++)
{
try
{
byte [] bytes = new byte [ 1500 ];
listener [i] .Receive(bytes,bytes.Length,SocketFlags.None);
if (bytes [ 0 ]。ToString()!=
{
// 当我通过客户端发送数据时不在这里
string st = Encoding.UTF8.GetString(字节);
st + = =;
}
}
catch (例外c){}
}
Thread.Sleep( 100
}



客户:

 尝试 
{
s = 套接字(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
int port = int .Parse(txtPort.Text);
s.Connect(txtIP.Text,port);
toolStripStatusLabel1.Text = 已连接到 + txtIP.Text;
}
catch (例外c){
MessageBox.Show(c.ToString());
}

private void button1_Click( object sender,EventArgs e)
{
// 当我向其发送数据时,服务器上没有任何反应
string str = txtmobileNo.Text + | + txtAmount.Text;
s.Send(Encoding.UTF8.GetBytes(str), 0 ,str.Length,SocketFlags.None);

}



请帮助。

解决方案

这样更容易改为使用 System.Net.Sockets.TcpClient和System.Net.Sockets.TcpListener 来代替:

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx [ ^ ],

http:// msdn .microsoft.com / zh-cn / library / system.net.sockets.tcplistener.aspx [ ^ ]。



为了成功,它至关重要你如何使用线程,特别是在服务器端。操作的模式应该是这样的:在服务端,你需要两个独立的线程:一个接受新的客户端连接(让我们称之为监听线程),另一个在一些应用程序之后写入和从NetworkStream读取数据你在循环中使用所有可用的远程(客户端)套接字开发的级别协议(让我们称之为通信线程)。



对于某些想法,请更详细地看看我过去的答案:

来自同一端口号码的多个客户端 [ ^ ],

业余问题在套接字编程中 [ ^ ]。



祝你好运,

-SA

I tried this:
Server:

IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
for (int i = 0; i < max_clients; i++)
{
    endpoint[i] = new IPEndPoint(ipAddress, port_starting + i);
    listener[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    listener[i].Bind(endpoint[i]);
    listener[i].Listen(100);
}

while(true){
            for (int i = 0; i < max_clients; i++)
            {
                try
                {
                    byte[] bytes = new byte[1500];
                    listener[i].Receive(bytes, bytes.Length, SocketFlags.None);
                    if (bytes[0].ToString() != "")
                    {
                    // not going here when I sent data by client
                        string st = Encoding.UTF8.GetString(bytes);
                        st += "="; 
                    }
                }
                catch (Exception c) { }
            }
Thread.Sleep(100)
}


Client:

try
{
    s = new Socket(AddressFamily.InterNetwork,
                   SocketType.Stream,
                   ProtocolType.Tcp);
    int port = int.Parse(txtPort.Text);
    s.Connect(txtIP.Text, port);
    toolStripStatusLabel1.Text = "Connected to " + txtIP.Text;
 }
catch (Exception c) {
    MessageBox.Show(c.ToString());
}

       private void button1_Click(object sender, EventArgs e)
        {
//nothing happens on server when I sent data to it
                string str = txtmobileNo.Text + "|" + txtAmount.Text;
                s.Send(Encoding.UTF8.GetBytes(str), 0, str.Length, SocketFlags.None);
           
}


Please help.

解决方案

It''s much easier to do the same using System.Net.Sockets.TcpClient and System.Net.Sockets.TcpListener instead:
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx[^],
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx[^].

For success, it''s critically important how you use threading, especially on server side. The schema of the operation should be like this: on the service side, you need two separate threads: one accepts new client connections (let''s call it listening thread), another one writes and reads data to/from NetworkStream following some application-level protocol you develop in cycle with all available remote (client''s) sockets (let''s call it communication thread).

For some ideas, please see my past answers with a lot more detail:
Multple clients from same port Number[^],
an amateur question in socket programming[^].

Good luck,
—SA


这篇关于如何为多个客户端制作简单的Socket Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆