Socket服務端:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SocketServer
{
public static Socket listenSocket;//監聽Socket
public static List<Socket> clientList = new List<Socket>();//客戶端列表
static void Main(string[] args)
{
//創建監聽Socket,并綁定ip
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
listenSocket.Bind(ip);
//設定監聽最大數量
listenSocket.Listen(100);
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start();
Console.ReadKey();
}
static void Listen()
{
Console.WriteLine("開始監聽");
while(true)
{
//開始監聽,若監聽到訪問則創建一個Socket表示與其的連接
Socket newSocket = listenSocket.Accept();
Console.WriteLine("有客戶端連接");
//告訴其他客戶端,有客戶端登錄
foreach(Socket socket in clientList)
{
socket.Send(new UTF8Encoding().GetBytes(newSocket.RemoteEndPoint.ToString() + "已經上線"));
}
//添加至列表
clientList.Add(newSocket);
//創建線程監聽客戶端發來的消息
Thread thread = new Thread(ReceiveMsg);
thread.IsBackground = true;
thread.Start(newSocket);
}
}
static void ReceiveMsg(Object Obj_)
{
Socket socket = (Socket)Obj_;
while (true)
{
try
{
byte[] bs = new byte[1024];
socket.Receive(bs);
Console.WriteLine(socket.RemoteEndPoint.ToString() + ":" + new UTF8Encoding().GetString(bs) + "\n");
}
catch
{
Console.WriteLine("有客戶端掉線");
clientList.Remove(socket);
return;
}
}
}
}
Socket客戶端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SockClient
{
public static Socket socket;
static void Main(string[] args)
{
//創建代表本地的socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//創建要連接的ip并嘗試連接該ip
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
socket.Connect(ip);
Thread thread = new Thread(ReceiveServerMessage);
thread.IsBackground = true;
thread.Start();
while(true)
{
string content = Console.ReadLine();
//發送消息
socket.Send(new UTF8Encoding().GetBytes(content));
}
}
static void ReceiveServerMessage()
{
while(true)
{
//接收來自服務端的消息
byte[] bs = new byte[1024];
socket.Receive(bs);
Console.WriteLine(socket.RemoteEndPoint.ToString() + ":" + new UTF8Encoding().GetString(bs) + "\n");
}
}
}