本文實例為大家分享了c#使用socket實現局域網聊天的具體代碼,供大家參考,具體內容如下
先運行一個java寫的局域網聊天,效果圖如下
后使用c#圖形修改如下:
c#代碼:
servlet服務端
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
using system; using system.collections.generic; using system.drawing; using system.windows.forms; using system.net; using system.net.sockets; using system.threading; using system.io; using system.text; using system.text.regularexpressions; namespace server { public partial class mainform : form { private tcplistener listener; private dictionary< string ,tcpclient> socketlist; private bool tag = true ; private stringbuilder charlist; public mainform() { initializecomponent(); control.checkforillegalcrossthreadcalls = false ; } void bu_startclick( object sender, eventargs e) { cb_chatlist.items.clear(); selectchat.text= "" ; int port = 8888; //創建服務端,并且啟動 try { listener = new tcplistener(ipaddress.parse(ipaddress()),port); listener.start(); bu_start.enabled = false ; bu_stop.enabled = true ; } catch (exception ex) { messagebox.show( "服務器啟動失敗, 原因:" +ex.message); bu_start.enabled = true ; bu_stop.enabled = false ; return ; } selectchat.text = "服務器啟動成功,訪問ip:" +ipaddress()+ " 端口號:" +port; //記錄住連接的客戶端 socketlist = new dictionary< string ,tcpclient>(); charlist = new stringbuilder(); //使用多線程,用于多個客戶端接入 thread th = new thread( new threadstart(executetask)); th.start(); } public void executetask() { while (tag) { //等待用戶連接 tcpclient client = null ; try { client = listener.accepttcpclient(); } catch (exception) { } thread th = new thread(executeread); th.start(( object )client); } } public void executeread( object pamars) { //永久監聽讀取客戶端 tcpclient client = pamars as tcpclient; while (tag) { networkstream ns = client.getstream(); streamreader sr = new streamreader(ns); string msg = string .empty; string people = string .empty; try { msg = sr.readline(); if (msg.indexof( "<clientname>" )!=-1) { msg = regex.split(msg, "=" )[1]; cb_chatlist.items.add(msg); charlist.append(msg).append( "<@>" ); socketlist.add(msg,client); msg = "<br>歡迎【" +msg+ "】光臨<br>" ; } selectchat.appendtext(msg.replace( "<br>" , "\r\n" )); sendmsg( string .empty,msg); } catch (exception) { //messagebox.show(ex.message.tostring()); break ; } } } public void sendmsg( string target, string msg) { if ( string .empty!=target) { tcpclient client = socketlist[target]; streamwriter sw = new streamwriter(client.getstream()); sw.writeline(msg); sw.flush(); } else { dictionary< string ,tcpclient>.keycollection keycoll = socketlist.keys; foreach ( string name in keycoll) { streamwriter sw = new streamwriter(socketlist[name].getstream()); sw.writeline(msg+ "<@=@>" +charlist.tostring()); sw.flush(); } } } /*根據計算名獲取ip地址*/ public string ipaddress() { ipaddress[] address = dns.gethostaddresses(dns.gethostname()); return address[2].tostring(); } void serverfromformclosing( object sender, formclosingeventargs e) { e.cancel = false ; if (tag) tag = false ; if (listener!= null ) listener.stop(); } void bu_stopclick( object sender, eventargs e) { bu_start.enabled = true ; bu_stop.enabled = false ; if (tag) tag = false ; if (listener!= null ) listener.stop(); } } } |
client客戶端
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
using system; using system.drawing; using system.windows.forms; using system.threading; using system.net; using system.net.sockets; using system.io; using system.text; using system.text.regularexpressions; namespace client { public partial class mainform : form { private system.windows.forms.timer closewindowtimer; private streamreader sr; private streamwriter sw; private tcpclient tc; private clientlong cl; private bool tag = true ; public mainform(tcpclient tcp,clientlong clo) { cl = clo; tc = tcp; initializecomponent(); control.checkforillegalcrossthreadcalls = false ; bu_simple.hide(); } void clientfromload( object sender, eventargs e) { piaycheckedchanged(); } /*事件方法*/ public void piaycheckedchanged() { closewindowtimer = new system.windows.forms.timer(); closewindowtimer.interval = 1000; closewindowtimer.tick += new eventhandler(theout); closewindowtimer.start(); } /*執行的事件*/ public void theout( object source, eventargs e) { //這里單獨開一個線程用來顯示信息 try { thread t1 = new thread( new threadstart(readmsg)); t1.start(); } catch (exception) { } } void readmsg() { if (tag && tc!= null ){ sr = new streamreader(tc.getstream()); string msg = sr.readline(); string [] address = regex.split(msg, "<@=@>" ); chattext.appendtext(address[0].replace( "<br>" , "\r\n" )); address = regex.split(address[1], "<@>" ); cb_chatlist.items.clear(); foreach ( string s in address) { if (! string .isnullorempty(s) && s != cl.clientname) cb_chatlist.items.add(s); } } } void button1click( object sender, eventargs e) { if ( string .isnullorempty(textbox2.text)){ messagebox.show( "請輸入消息" ); return ; } sw = new streamwriter(tc.getstream()); sw.writeline( "<br>" +cl.clientname+ " " +datetime.now.tostring( "yyyy-mm-dd hh:mm:ss" )+ "<br> " +textbox2.text); textbox2.text = "" ; sw.flush(); } void bu_exitclick( object sender, eventargs e) { mainformformclosing( null , null ); } void button2click( object sender, eventargs e) { chattext.text = "" ; } void mainformformclosing( object sender, formclosingeventargs e) { closewindowtimer.stop(); cl.close(); tag = false ; if (sr!= null ) sr.close(); if (sw!= null ) sw.close(); } void bu_simpleclick( object sender, eventargs e) { string selected = cb_chatlist.text; if (selected== null ) { messagebox.show( "請選擇單聊對象" ); return ; } } } } |
補充:
1.上傳下載文件、聊天表情、私聊、踢人.......都是可以擴展的功能。
只是目前還沒有可執行的思路,希望有相同愛好者多多提出寶貴意見,我會繼續關注。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hubiao_0618/article/details/35796919