C#TCP,網路流通訊執行個體

來源:互聯網
上載者:User

標籤:stat   buffers   ipad   linq   port   client   space   remote   catch   

服務端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ceshi1
{
class Program
{
static void Main(string[] args)
{
string sendString = null;//要發送的字串
byte[] sendData = null;//要發送的位元組數組
TcpClient client = null;//TcpClient執行個體
NetworkStream stream = null;//網路流
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");//遠程主機IP
int remotePort = 11000;//遠程主機連接埠
while (true)//死迴圈
{
sendString = Console.ReadLine();//擷取要發送的字串
sendData = Encoding.Default.GetBytes(sendString);//擷取要發送的位元組數組
client = new TcpClient();//執行個體化TcpClient
try
{
client.Connect(remoteIP, remotePort);//串連遠程主機
}
catch (System.Exception ex)
{
Console.WriteLine("連線逾時,伺服器沒有響應!");//串連失敗
Console.ReadKey();
return;
}
stream = client.GetStream();//擷取網路流
stream.Write(sendData, 0, sendData.Length);//將資料寫入網路流
stream.Close();//關閉網路流
client.Close();//關閉用戶端
}
}
}
}

客戶接收端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ceshi
{
class Program
{
static void Main(string[] args)
{
TcpClient client = null;
NetworkStream stream = null;
byte[] buffer = null;
string receiveString = null;
IPAddress localIP = IPAddress.Parse("127.0.0.1");
int localPort = 11000;
TcpListener listener = new TcpListener(localIP, localPort);//用本地IP和連接埠執行個體化Listener
listener.Start();//開始監聽
while (true)
{
client = listener.AcceptTcpClient();//接受一個Client
buffer = new byte[client.ReceiveBufferSize];
stream = client.GetStream();//擷取網路流
stream.Read(buffer, 0, buffer.Length);//讀取網路流中的資料
stream.Close();//關閉流
client.Close();//關閉Client
receiveString = Encoding.Default.GetString(buffer).Trim(‘\0‘);//轉換成字串
Console.WriteLine(receiveString);
}
}
}
}

C#TCP,網路流通訊執行個體

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.