C# Tcp協議收發資料(TCPClient發,Socket收)

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   for   strong   on   資料   

運行這個程式前需要先關閉Windows防火牆,Win7系統關閉防火牆的方法是在控制台的“控制台\系統和安全\Windows 防火牆\自訂設定”路徑中,將“家庭或工作(專用)網路位置設定”和“公用網路位置設定”下面的選項都選到“關閉Windows防火牆(不推薦)”。

1.介面設計

左側為發送資料的輸入框,單擊“發送資料”把資料發送到指定IP地址的指定連接埠號碼。(本例中,IP地址和連接埠號碼都被寫死到代碼中)

2.程式碼

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.IO;using System.Threading;namespace TcpClientTest{    public partial class FormMain : Form    {        public FormMain()        {            InitializeComponent();        }        private void FormMain_Load(object sender, EventArgs e)        {            //初始化控制項            txtSendMssg.Text = "測試資料";            //開啟Listener開始監聽            Thread thrListener = new Thread(new ThreadStart(Listen));            thrListener.Start();        }        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)        {            //強制關閉程式(強行終止Listener)            Environment.Exit(0);        }        //發送資料        private void btnSend_Click(object sender, EventArgs e)        {            TcpClient tcpClient = new TcpClient();            //tcpClient.Connect(IPAddress.Parse("170.0.0.78"), 2014);            tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 2014);            NetworkStream ntwStream = tcpClient.GetStream();            if (ntwStream.CanWrite)            {                Byte[] bytSend = Encoding.UTF8.GetBytes(txtSendMssg.Text);                ntwStream.Write(bytSend, 0, bytSend.Length);            }            else            {                MessageBox.Show("無法寫入資料流");                ntwStream.Close();                tcpClient.Close();                return;            }            ntwStream.Close();            tcpClient.Close();        }        //監聽資料        private void Listen()        {            Socket listener = new Socket(AddressFamily.InterNetwork,                 SocketType.Stream, ProtocolType.Tcp);            listener.Bind(new IPEndPoint(IPAddress.Any, 2014));            //不斷監聽連接埠            while (true)            {                listener.Listen(0);                Socket socket = listener.Accept();                NetworkStream ntwStream = new NetworkStream(socket);                StreamReader strmReader = new StreamReader(ntwStream);                Invoke(new PrintRecvMssgDelegate(PrintRecvMssg),                     new object[] { strmReader.ReadToEnd() });                socket.Close();            }            //程式的listener一直不關閉            //listener.Close();        }        //線程內向文字框txtRecvMssg中添加字串及委託        private delegate void PrintRecvMssgDelegate(string s);        private void PrintRecvMssg(string info)        {            txtRecvMssg.Text += string.Format("[{0}]:{1}\r\n",                 DateTime.Now.ToLongTimeString(), info);        }    }}

3.運行效果

在發送資料的文字框中分別輸入“千山鳥飛絕”、“萬徑人蹤滅”、“孤舟蓑笠翁”、“獨釣寒江雪”四句話,輸完一句話,單擊一次“發送資料”按鈕,就可以在接收資料裡看到這四句話了。上面代碼中,資訊的發送時通過TcpClient串連到127.0.0.1的2014連接埠,資訊的接收是通過Listen函數不斷監聽原生2014連接埠實現的。從自己建立的線程中修改控制項資訊,用到了委託。

END

C# Tcp協議收發資料(TCPClient發,Socket收)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.