TCP实现内网连接到外网,外网发送数据给内网的例子

来源:互联网 发布:mac mini顶配 编辑:程序博客网 时间:2024/05/16 10:47

客户端代码:

内网用TCP与外网进行链接,外网收到消息后转回此消息,彼此互相通信

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.Sockets;
using System.Net;
using System.Threading;

namespace mytcpchat
{
    public partial class Form1 : Form
    {
        Socket c;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
        }
         public void Client(IPEndPoint ServerIPEP)
        {
            try
            {
                c = new Socket(ServerIPEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                c.Connect((EndPoint)ServerIPEP);
                c.Send(System.Text.Encoding.Default.GetBytes("这是一个测试消息"));
                byte[] data = new byte[2048];
                int rect = c.Receive(data);
                byte[] chat = new byte[rect];
                Buffer.BlockCopy(data, 0, chat, 0, rect);
                MessageBox.Show(System.Text.Encoding.Default.GetString(chat));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Client(new IPEndPoint(IPAddress.Parse("220.194.57.122"), 5566));
        }
    }

 

服务端例子:

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.Sockets;
using System.Net;
using System.Threading;
namespace mytcpserver
{
    public partial class Form1 : Form
    {
        Socket s;
        IPEndPoint ServerIPEP;
        public Form1()
        {
            InitializeComponent();
        }
         public void  Server(int port)
        {
            ServerIPEP = new IPEndPoint(IPAddress.Any, port);
            s = new Socket(ServerIPEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            s.Bind((EndPoint)ServerIPEP);
            s.Listen(10);
            while (true)
            {
                Socket uc = s.Accept();
                byte[] data = new byte[2048] ;
                int rect = uc.Receive(data);
                byte[] chat = new byte[rect] ;
                Buffer.BlockCopy(data, 0, chat, 0, rect);
                MessageBox.Show("接收到来及客户端的消息"+uc.RemoteEndPoint.ToString()+System.Text.Encoding.Default.GetString(chat));
                uc.Send(chat);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Server(5566);
        }
    }
}

原创粉丝点击