Socket小案例

來源:互聯網
上載者:User

標籤:

1.首先是伺服器的編寫:

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

namespace Server
{
class Program
{
private static Socket server;
static void Main(string[] args)
{
//建立一個通訊端
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//綁定連接埠
server.Bind(new IPEndPoint(IPAddress.Any, 10001));
//監聽
server.Listen(10);//監聽個數

//不斷的監聽
while(true)
{
Socket client = server.Accept();//接收用戶端連結的資訊
Console.WriteLine("有用戶端連入");

//對用戶端中的通訊端傳遞過來的資訊進行處理
ReceiveMessage(client);
}
}

private static void ReceiveMessage(Socket client)
{
try
{
byte[] buffer = new byte[1024];//作為資料緩衝

int size = client.Receive(buffer);

//哪一個用戶端串連的,以及輸出的是什麼
Console.WriteLine(client.RemoteEndPoint.ToString() + ":" + Encoding.UTF8.GetString(buffer, 0, size));
ReceiveMessage(client);
}
catch (Exception)
{

Console.WriteLine("用戶端斷開了");
}

}
}
}

 

2.用戶端的編寫:

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

namespace Client
{
class Program
{
private static Socket client;
private static byte[] bytearray = new byte[1024];
static void Main(string[] args)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect("127.0.0.1", 10001);

//開始從連結的socket中非同步接收資料
client.BeginReceive(bytearray, 0, 1024, SocketFlags.None, ReceiveCallBack, client);

Input();
}

private static void Input()
{
string txt = Console.ReadLine();

if(txt.Trim().Equals(string.Empty))
{
Console.WriteLine("按任意鍵退出");

Console.Read();
return;
}

byte[] array = Encoding.UTF8.GetBytes(txt);
client.Send(array);
Input();


}

private static void ReceiveCallBack(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
try
{
int size = client.EndReceive(ar);

Console.WriteLine(Encoding.UTF8.GetString(bytearray, 0, size));

client.BeginReceive(bytearray, 0, 1024, SocketFlags.None, ReceiveCallBack, client);
}
catch (Exception)
{

Console.WriteLine("伺服器把你給踢了!");
}
}
}
}

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.