C# TCP/IP 服務端 和 客戶端

服務端
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace TcpIpServer
{
class TcpIpServerEx
{
public EndPoint RemoteEndPoint { get; private set; } //當前客戶端的網絡結點

Thread threadwatch = null;//負責監聽客戶端的線程
Socket socket = null;//負責監聽客戶端的套接字
// Dictionary<ip和端口, Socket> 定義一個集合,存儲客戶端信息
public Dictionary<EndPoint, Socket> dic = new Dictionary<EndPoint, Socket> { };

private StringBuilder msg = new StringBuilder();
public string Msg
{
get { return msg.ToString(); }
private set
{
msg.AppendLine(value);
Console.WriteLine(value + "\r\n");
}

}

private TcpIpServerEx() { }
public TcpIpServerEx( int port=11000)
{
//定義一個套接字用於監聽客戶端發來的消息,包含三個參數(IP4尋址協議,流式鏈接,Tcp協議)
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//將IP地址和端口號綁定到網絡節點point上
IPEndPoint point = new IPEndPoint(IPAddress.Any, port);//設置服務器端口,IP是本程序所在PC的內網IP

//監聽綁定的網絡節點
socket.Bind(point);

//將套接字的監聽隊列長度限制爲20
socket.Listen(20);

//建立一個監聽線程
threadwatch = new Thread(watchconnecting);

//將窗體線程設置爲與後臺同步,隨着主線程結束而結束
threadwatch.IsBackground = true;

//啓動線程
threadwatch.Start();

//啓動線程後顯示相應提示
Msg = ("開始監聽客戶端傳來的信息!" + "\r\n");
}

//監聽客戶端發來的請求
private void watchconnecting()
{
Socket connection = null;
while (true) //持續不斷監聽客戶端發來的請求
{
try
{
connection = socket.Accept();
}
catch (Exception ex)
{
Msg =(ex.Message); //提示套接字監聽異常
break;
}

//讓客戶顯示"鏈接成功的"的信息
string sendmsg = "鏈接服務端成功!你的IP是" + connection.RemoteEndPoint;
byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
connection.Send(arrSendMsg);


RemoteEndPoint = connection.RemoteEndPoint; //客戶端網絡結點號
Msg = ("成功與" + RemoteEndPoint + "客戶端創建鏈接!\t\n"); //顯示與客戶端鏈接狀況
dic.Add(RemoteEndPoint, connection); //添加客戶端信息


//建立一個通訊線程
ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
Thread thread = new Thread(pts);
thread.IsBackground = true;//設置爲後臺線程,隨着主線程退出而退出
thread.Start(connection);//啓動線程
}
}

///
/// 接收客戶端發來的信息
///
///客戶端套接字對象
private void recv(object socketclientpara)
{

Socket socketServer = socketclientpara as Socket;
while (true)
{
//建立一個內存緩衝區 其大小爲1024*1024字節 即1M
byte[] arrServerRecMsg = new byte[1024 * 1024];
//將接收到的信息存入到內存緩衝區,並返回其字節數組的長度
try
{
int length = socketServer.Receive(arrServerRecMsg);

//將機器接受到的字節數組轉換爲人能夠讀懂的字符串
string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

//將發送的字符串信息附加到文本框txtMsg上
Msg = ("客戶端:" + GetCurrentTime() + socketServer.RemoteEndPoint +"的消息:"+ strSRecMsg + "\r\n");
}
catch (Exception ex)
{
Msg = ("客戶端:" + GetCurrentTime() + socketServer.RemoteEndPoint + "已經中斷鏈接" + "\r\n"); //提示套接字監聽異常
//listBoxOnlineList.Items.Remove(socketServer.RemoteEndPoint.ToString());//從listbox中移除斷開鏈接的客戶端
socketServer.Close();//關閉以前accept出來的和客戶端進行通訊的套接字
break;
}
}


}


//獲取當前系統時間
private string GetCurrentTime()
{
string timeStr = System.DateTime.Now.ToString("yyyy年MM月dd日hh時mm分ss秒fff毫秒。");
return timeStr;
}

/// <summary>
/// 發送信息到客戶端
/// </summary>
/// <param name="smallname"></param>
/// <param name="sendMsg">要發送的信息</param>
public void SentMsg(EndPoint endPoint,string sendMsg)
{

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sendMsg); //將要發送的信息轉化爲字節數組,由於Socket發送數據時是以字節的形式發送的
dic[endPoint].Send(bytes); //發送數據
Msg = (GetCurrentTime() + endPoint +"的消息:"+ sendMsg + "\r\n");
}
}
}

using System;
namespace TcpIpServer
{
class Program
{
static void Main(string[] args)
{
TcpIpServerEx s =new TcpIpServerEx();
while (true)
{
string strSend = Console.ReadLine();
if (strSend == "exit") break;
Console.WriteLine("s.dic.Count:"+ s.dic.Count);
if (s.dic.Count >0)
{
s.SentMsg(s.RemoteEndPoint,strSend);
}
}
}
}
}
客戶端
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace TcpIpClint
{
public class TcpIpClintEx
{
//建立 1個客戶端套接字 和1個負責監聽服務端請求的線程
Thread threadclient = null;
Socket socket = null;
List<IPEndPoint> mlist = new List<IPEndPoint>();
private StringBuilder msg = new StringBuilder();
public string Msg
{
get { return msg.ToString(); }
private set
{
msg.AppendLine(value);
Console.WriteLine(value + "\r\n");
}
}

public TcpIpClintEx(string ip, int port = 11000)
{
//定義一個套接字監聽
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//將獲取的IP地址和端口號綁定在網絡節點上
IPEndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
Msg = "正在鏈接服務器 " + ip + ":" + port;

try
{
//客戶端套接字鏈接到網絡節點上,用的是Connect
socket.Connect(point);
}
catch (Exception)
{
Msg = ("鏈接失敗\r\n");
return;
}

threadclient = new Thread(recv);
threadclient.IsBackground = true;
threadclient.Start();
}

// 接收服務端發來信息的方法
private void recv()//
{
while (true)//持續監聽服務端發來的消息
{
try
{
//定義一個1M的內存緩衝區,用於臨時性存儲接收到的消息
byte[] arrRecvmsg = new byte[1024 * 1024];

//將客戶端套接字接收到的數據存入內存緩衝區,並獲取長度
int length = socket.Receive(arrRecvmsg);

//將套接字獲取到的字符數組轉換爲人能夠看懂的字符串
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);

Msg = ("服務器:" + GetCurrentTime() + "IP:" + socket.RemoteEndPoint + ",的消息:" + strRevMsg + "\r\n\n");
}
catch (Exception ex)
{
Msg = ("遠程服務器已經中斷鏈接" + "\r\n");
break;
}
}
}

//獲取當前系統時間
private string GetCurrentTime()
{
string timeStr = System.DateTime.Now.ToString("yyyy年MM月dd日hh時mm分ss秒fff毫秒。");
return timeStr;
}

//發送字符信息到服務端的方法
public void ClientSendMsg(string sendMsg)
{
//將輸入的內容字符串轉換爲機器能夠識別的字節數組
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//調用客戶端套接字發送字節數組
socket.Send(arrClientSendMsg);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;

namespace TcpIpClint
{
class Program
{
static void Main(string[] args)
{
TcpIpClintEx tcpIpClintEx =new TcpIpClintEx("122.112.226.109");

while (true)
{
string strSend = Console.ReadLine();
if (strSend == "exit") break;
tcpIpClintEx.ClientSendMsg(strSend);
}
}
}
}
————————————————

原文連接:https://blog.csdn.net/u013628121/article/details/82968706數組

相關文章
相關標籤/搜索