socket 指向外网IP

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);
        }
    }
}

 说明:socket端口需要指向在路由器映射的端口

 转载来源:http://topic.csdn.net/u/20090605/16/3FE7D4B8-1C0F-4B0A-B389-DDAE58B7477C.html

你可能感兴趣的:(C#,Socket,.net,C,C++,C#)