c# socket網(wǎng)絡(luò)編程接收發(fā)送數(shù)據(jù)示例代碼
代碼分2塊,server端:
class Program
{
static void Main(string[] args)
{
TcpListener lsner = new TcpListener(9000);
lsner.Start();
Console.WriteLine("started in port: 9000");
while (true)
{
TcpClient client=lsner.AcceptTcpClient();
Console.WriteLine("new client received. hashcode: {0}", client.GetHashCode());
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessTcpClient), client);
}
Console.ReadKey();
}
private static void ProcessTcpClient(object state)
{
TcpClient client=state as TcpClient;
if(client==null)
Console.WriteLine("client is null");
NetworkStream ns=client.GetStream();
StreamWriter sw = new StreamWriter(ns);
sw.WriteLine("Welcome.");
sw.Flush();
sw.Close();
client.Close();
}
client端:
class Program
{
static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint ep=new IPEndPoint(address, 9000);
TcpClient client = new TcpClient();
client.Connect(ep);
NetworkStream ns=client.GetStream();
StreamReader sr = new StreamReader(ns);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
sr.Dispose();
ns.Close();
ns.Dispose();
client.Close();
Console.ReadKey();
}
}
![]() |
相關(guān)文章
深入多線程之:Reader與Write Locks(讀寫鎖)的使用詳解
本篇文章是對Reader與Write Locks(讀寫鎖)的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05C# Access數(shù)據(jù)庫增刪查改的簡單方法
這篇文章主要介紹了C# Access數(shù)據(jù)庫增刪查改的簡單方法,有需要的朋友可以參考一下2014-01-01詳談C# 圖片與byte[]之間以及byte[]與string之間的轉(zhuǎn)換
下面小編就為大家?guī)硪黄斦凜# 圖片與byte[]之間以及byte[]與string之間的轉(zhuǎn)換。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02