c#實現多線程區域網路聊天系統

來源:互聯網
上載者:User

c#實現多線程區域網路聊天系統

   這篇文章主要介紹了c#實現多線程區域網路聊天系統的相關代碼,有此方面需求的小夥伴可以參考下。

  覺得好有點協助就頂一下啦。

  socke編程,支援多用戶端,多線程操作避免介面卡死。

  開啟socket

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

private void button1_Click(object sender, EventArgs e)

{

try

{

int port = int.Parse(txt_port.Text);

string host = txt_ip.Text;

//建立終結點

IPAddress ip = IPAddress.Parse(host);

IPEndPoint ipe = new IPEndPoint(ip, port);

//建立Socket並開始監聽

newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立一個Socket對象,如果用UDP協議,則要用SocketTyype.Dgram類型的通訊端

newsock.Bind(ipe); //綁定EndPoint對象

newsock.Listen(0); //開始監聽

//為建立立的串連建立新的Socket

acceptClientThread = new Thread(new ThreadStart(AcceptClient));

acceptClientThread.Start();

SetText("開始監聽");

}

catch (Exception exp)

{

CommonFunction.WriteLog(exp, exp.Message);

}

}

  監控連接埠,接收用戶端

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/// <summary>

/// 接受用戶端,可接受多個用戶端同時連入,並對連入的用戶端註冊到用戶端列表

/// </summary>

public void AcceptClient()

{

try

{

while (true)

{

Socket client = newsock.Accept();

ip = client.Handle;

RegeistUser(client.Handle, client);

Thread clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));

object o = client;

clientThread.Start(o);

}

}

catch (Exception exp)

{

CommonFunction.WriteLog(exp, exp.Message);

}

}

  接收用戶端資料並廣播資料

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/// <summary>

/// 接收用戶端資料並,轉寄到勘探端。

/// </summary>

public void ReceiveData(object o)

{

try

{

while (true)

{

Socket client = (Socket)o;

string recvStr = "";

byte[] recvBytes = new byte[1024];

int bytes;

bytes = client.Receive(recvBytes, recvBytes.Length, 0); //從用戶端接受訊息

recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);

SendMessage(client, recvStr);

SetText(recvStr);

CommonFunction.WriteErrorLog(recvStr);

}

}

catch (Exception exp)

{

CommonFunction.WriteLog(exp, exp.Message);

}

}

  判斷是使用者註冊還是發送訊息

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/// <summary>

/// 判斷是使用者註冊還是發送訊息

/// </summary>

/// <param name="p_strMessage"></param>

public void SendMessage(Socket client,string p_strMessage)

{

if (p_strMessage.StartsWith("@"))

{

RegeistUser(p_strMessage, client);

}

else if (p_strMessage.StartsWith(">"))

{

 

DeleteClident(p_strMessage);

}

else

{

//SendMessageToTarget(p_strMessage);

SendAllMessage(p_strMessage);

}

}

  將socket註冊為指定使用者名稱

  ?

1

2

3

4

5

6

7

8

9

10

11

12

/// <summary>

/// 將socket註冊為指定使用者名稱

/// </summary>

/// <param name="user"></param>

/// <param name="ss"></param>

public void RegeistUser(string user, Socket ss)

{

user = user.Remove(0, 1);

userSocketDict.Add(user, ss);

SendOneMessage(ss, "歡迎" + user + "連入!");

RefreshClient();

}

  從用戶端字典中移除用戶端

  ?

1

2

3

4

5

6

7

8

9

10

/// <summary>

/// 從用戶端字典中移除用戶端

/// </summary>

/// <param name="p_strMessage"></param>

public void DeleteClident(string p_strMessage)

{

p_strMessage = p_strMessage.Remove(0, 1);

userSocketDict.Remove(p_strMessage);

RefreshClient();

}

  群發訊息

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

/// <summary>

/// 群發訊息

/// </summary>

/// <param name="p_strsend"></param>

public void SendAllMessage(string p_strsend)

{

//MessageBox.Show(p_strsend);

foreach (string item in userSocketDict.Keys)

{

byte[] bs = Encoding.UTF8.GetBytes(p_strsend);

userSocketDict[item].Send(bs, bs.Length, 0);

}

}

  給文字框賦值

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public delegate void SetTextHandler(string text);

/// <summary>

/// 給文字框賦值

/// </summary>

/// <param name="text"></param>

private void SetText(string text)

{

if (rich_back.InvokeRequired == true)

{

SetTextHandler set = new SetTextHandler(SetText);//委託的方法參數應和SetText一致

rich_back.Invoke(set, new object[] { text }); //此方法第二參數用於傳入方法,代替形參text

}

else

{

rich_back.Text += "\n" + text;

}

 

}

  連入伺服器

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

private void button1_Click(object sender, EventArgs e)

{

try

{

user = txt_name.Text;

int port = int.Parse(txt_port.Text);

string host = txt_ip.Text;

//建立終結點EndPoint

IPAddress ip = IPAddress.Parse(host);

IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和連接埠轉化為IPEndPoint的執行個體

//建立Socket並串連到伺服器

Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 建立Socket

cc = c;

c.Connect(ipe); //串連到伺服器

clientThread = new Thread(new ThreadStart(ReceiveData));

clientThread.Start();

//向伺服器發送本機使用者名稱,以便伺服器註冊用戶端

SendMessage("@" + txt_name.Text);

}

catch (ArgumentException ex)

{

Console.WriteLine("argumentNullException:{0}", ex);

}

catch (SocketException exp)

{

Console.WriteLine("SocketException:{0}",exp);

}

}

  向伺服器發送訊息

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

private void button3_Click(object sender, EventArgs e)

{

if (""==txt_target.Text)

{

MessageBox.Show("未選擇對話人物");

return;

}

//向伺服器發送資訊

string sendStr = txt_name.Text + "@" + target + ":" + txt_message.Text;

SendMessage(sendStr);

rch_back.Text += "\n" + sendStr;

txt_message.Text = "";

}

  隱藏

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

private void button2_Click(object sender, EventArgs e)

{

try

{

SendMessage(">" + txt_name.Text);

//cc.Disconnect(true);

//cc.Shutdown(SocketShutdown.Both);

//cc.Close();

}

catch (Exception exp)

{

CommonFunction.WriteLog(exp, exp.Message);

}

}

  以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.