1. 程式人生 > >C# Socket 通信

C# Socket 通信

bytes ner close string 存儲 限制 bre bug 發送數據

client

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace CsocketClient

{
public partial class Main : Form
{
//創建 1個客戶端套接字 和1個負責監聽服務端請求的線程
Thread threadclient = null;
Socket socketclient = null;
public Main()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
//關閉對文本框的非法線程操作檢查
TextBox.CheckForIllegalCrossThreadCalls = false;

this.btnSendMessage.Enabled = false;
this.btnSendMessage.Visible = false;

// this.txtDebugInfo.Visible = false;
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnConnection_Click(object sender, EventArgs e)

{
this.btnConnection.Enabled = false;
//定義一個套接字監聽
socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//獲取文本框中的IP地址
IPAddress address = IPAddress.Parse("127.0.0.1");

//將獲取的IP地址和端口號綁定在網絡節點上
IPEndPoint point = new IPEndPoint(address, 8098);

try
{
//客戶端套接字連接到網絡節點上,用的是Connect
socketclient.Connect(point);
this.btnSendMessage.Enabled = true;
this.btnSendMessage.Visible = true;
this.txtMessage.Visible = true;
}
catch (Exception)
{
Debug.WriteLine("連接失敗\r\n");

this.txtDebugInfo.AppendText("連接失敗\r\n");
return;
}

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

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

//將套接字獲取到的字符數組轉換為人可以看懂的字符串
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
if (x == 1)
{
this.txtDebugInfo.AppendText("服務器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
Debug.WriteLine("服務器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
}
else
{
this.txtDebugInfo.AppendText(strRevMsg + "\r\n\n");
Debug.WriteLine(strRevMsg + "\r\n\n");
x = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("遠程服務器已經中斷連接" + "\r\n\n");
Debug.WriteLine("遠程服務器已經中斷連接" + "\r\n");
break;
}
}
}

//獲取當前系統時間
DateTime GetCurrentTime()
{
DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
return currentTime;
}

//發送字符信息到服務端的方法
void ClientSendMsg(string sendMsg)
{
//將輸入的內容字符串轉換為機器可以識別的字節數組
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//調用客戶端套接字發送字節數組
socketclient.Send(arrClientSendMsg);
//將發送的信息追加到聊天內容文本框中
Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
this.txtDebugInfo.AppendText("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
}

private void btnSendMessage_Click_1(object sender, EventArgs e)
{
//調用ClientSendMsg方法 將文本框中輸入的信息發送給服務端
ClientSendMsg(this.txtMessage.Text.Trim());
this.txtMessage.Clear();
}
}
}

server

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

namespace Csocket
{
public class Program
{
// 創建一個和客戶端通信的套接字
static Socket socketwatch = null;
//定義一個集合,存儲客戶端信息
static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

public static void Main(string[] args)
{
//定義一個套接字用於監聽客戶端發來的消息,包含三個參數(IP4尋址協議,流式連接,Tcp協議)
socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//服務端發送信息需要一個IP地址和端口號
IPAddress address = IPAddress.Parse("127.0.0.1");
//將IP地址和端口號綁定到網絡節點point上
IPEndPoint point = new IPEndPoint(address, 8098);
//此端口專門用來監聽的

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

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

//負責監聽客戶端的線程:創建一個監聽線程
Thread threadwatch = new Thread(watchconnecting);

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

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

Console.WriteLine("開啟監聽。。。");
Console.WriteLine("點擊輸入任意數據回車退出程序。。。");
Console.ReadKey();
Console.WriteLine("退出監聽,並關閉程序。");
}

//監聽客戶端發來的請求
static void watchconnecting()
{
Socket connection = null;

//持續不斷監聽客戶端發來的請求
while (true)
{
try
{
connection = socketwatch.Accept();
}
catch (Exception ex)
{
//提示套接字監聽異常
Console.WriteLine(ex.Message);
break;
}

//獲取客戶端的IP和端口號
IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

//讓客戶顯示"連接成功的"的信息
string sendmsg = "連接服務端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
connection.Send(arrSendMsg);

//客戶端網絡結點號
string remoteEndPoint = connection.RemoteEndPoint.ToString();
//顯示與客戶端連接情況
Console.WriteLine("成功與" + remoteEndPoint + "客戶端建立連接!\t\n");
//添加客戶端信息
clientConnectionItems.Add(remoteEndPoint, connection);

//IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort);
IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

//創建一個通信線程
ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
Thread thread = new Thread(pts);
//設置為後臺線程,隨著主線程退出而退出
thread.IsBackground = true;
//啟動線程
thread.Start(connection);
}
}

/// <summary>
/// 接收客戶端發來的信息,客戶端套接字對象
/// </summary>
/// <param name="socketclientpara"></param>
static 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上
Console.WriteLine("客戶端:" + socketServer.RemoteEndPoint + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n");

socketServer.Send(Encoding.UTF8.GetBytes("測試server 是否可以發送數據給client "));
}
catch (Exception ex)
{
clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

Console.WriteLine("Client Count:" + clientConnectionItems.Count);

//提示套接字監聽異常
Console.WriteLine("客戶端" + socketServer.RemoteEndPoint + "已經中斷連接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
//關閉之前accept出來的和客戶端進行通信的套接字
socketServer.Close();
break;
}
}
}


static DateTime GetCurrentTime()
{
DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
return currentTime;
}
}
}

C# Socket 通信