TCP實現內網連線到外網,外網傳送資料給內網的例子
客戶端程式碼:
內網用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);
}
}
}