通过TCP发送简单消息 [英] sending simple message through TCP

查看:250
本文介绍了通过TCP发送简单消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





以下代码在使用loopback ip的同一台计算机中完美运行,但如果我们在两台计算机之间尝试会导致问题。有什么建议吗?



谢谢。

NAS



客户端:

Hi ,

The following code work perfectly in in the same computer using the loopback ip ,but cause a problem if we try between two computers . Any suggestions ??

Thanks.
N.A.S

Client side:

private void button1_Click(object sender, EventArgs e)
       {
           client = new TcpClient();
           client.Connect("127.0.0.1", 8080);
       }
       TcpClient client;

       private void button2_Click(object sender, EventArgs e)
       {
           byte[] b = Encoding.Unicode.GetBytes(textBox1.Text);
           client.GetStream().Write(b, 0, Encoding.Unicode.GetByteCount(textBox1.Text));}









服务器端:





Server side:

private void rcv()

                    {
                        Int32 port = 8080;
                        IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            TcpListener ls = new TcpListener(localAddr,port); 
            ls.Start();
            TcpClient clientOne = ls.AcceptTcpClient();
           byte[] b = new byte[1024]; 
            while (true)
            {
                clientOne.GetStream().Read(b, 0, 1024);
                //MessageBox.Show(Encoding.Unicode.GetString(b));
                textBox1.Text = Encoding.Unicode.GetString(b);
            }
            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            new Thread(new ThreadStart(rcv)).Start();}

推荐答案

在C#中查看服务器和客户端示例的以下两个链接:

- 服务器 [ ^ ]

- 客户端 [ ^ ]



在上面的例子中,假设字符编码是ASCII(7位ASCII),因此,每个缓冲区都可以立即解码。如果您传输任何可能的多字节数据,您必须首先发明一些缓冲(例如,在解码之前读取所有数据)并且仅解码您正确解码的内容。



干杯

Andi
See the following two links for a server and a client example in C#:
- Server[^]
- Client[^]

In the examples above, the character encoding is assumed to be ASCII (7-bit ASCII), thus, each buffer can be decoded immediately. If you transport any potentially multi-byte data, you must first invent some buffering (e.g. read all data before decoding) and only decode what you properly can decode.

Cheers
Andi


你使用什么IP地址?如果客户端和服务器在同一个局域网中,你可以使用局域网IP地址,但如果不是在同一个局域网中,您的服务器必须使用唯一的全局IP地址.172.16.xx到172.31.xx,192.168.xx,10.xxx,这些IP地址只能在局域网中使用。如果您的路由找到您发送的数据包,其目的IP地址是以前的IP地址,它将丢弃它们。
what IP Address do you use?If the client and server are in the same LAN,you can use LAN ip address,but if they are not in the same LAN,your server must use the only global IP address.172.16.x.x to 172.31.x.x,192.168.x.x,10.x.x.x,these IP addresses can only be used in LAN.If your route find the data packets you send,whose destinaton IP addresses are the previous ones,it will discard them.


这篇关于通过TCP发送简单消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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