怎么使用Socket實現(xiàn)局域網(wǎng)聊天
局域網(wǎng)通常是分布在一個有限地理范圍內(nèi)的網(wǎng)絡(luò)系統(tǒng),一般所涉及的地理范圍只有幾公里。局域網(wǎng)專用性非常強,具有比較穩(wěn)定和規(guī)范的拓撲結(jié)構(gòu)。這篇文章主要為大家詳細介紹了C#使用Socket實現(xiàn)局域網(wǎng)聊天的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
C#代碼:
servlet服務(wù)端
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
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;
//創(chuàng)建服務(wù)端,并且啟動
try{
listener = new TcpListener(IPAddress.Parse(ipAddress()),port);
listener.Start();
bu_Start.Enabled = false;
bu_stop.Enabled = true;
}catch(Exception ex)
{
MessageBox.Show("服務(wù)器啟動失敗, 原因:"+ex.Message);
bu_Start.Enabled = true;
bu_stop.Enabled = false;
return;
}
selectChat.Text = "服務(wù)器啟動成功,訪問IP:"+ipAddress()+" 端口號:"+port;
//記錄住連接的客戶端
socketList = new Dictionary
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)
{
//永久監(jiān)聽讀取客戶端
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("
{
msg = Regex.Split(msg,"=")[1];
cb_chatList.Items.Add(msg);
charList.Append(msg).Append("<@>");
socketList.Add(msg,client);
msg = "
歡迎【"+msg+"】光臨
";
}
selectChat.AppendText(msg.Replace("
","\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
foreach (String name in keyColl)
{
StreamWriter sw = new StreamWriter(socketList[name].GetStream());
sw.WriteLine(msg+"<@=@>"+charList.ToString());
sw.Flush();
}
}
}
/*根據(jù)計算名獲取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客戶端
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();
}
/*執(zhí)行的事件*/
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("
","\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("
"+cl.clientName+" "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"
"+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;
}
}
}
}
補充:局域網(wǎng)、校園網(wǎng)安全維護方法
校園網(wǎng)絡(luò)分為內(nèi)網(wǎng)和外網(wǎng),就是說他們可以上學(xué)校的內(nèi)網(wǎng)也可以同時上互聯(lián)網(wǎng),大學(xué)的學(xué)生平時要玩游戲購物,學(xué)校本身有自己的服務(wù)器需要維護;
在大環(huán)境下,首先在校園網(wǎng)之間及其互聯(lián)網(wǎng)接入處,需要設(shè)置防火墻設(shè)備,防止外部攻擊,并且要經(jīng)常更新抵御外來攻擊;
由于要保護校園網(wǎng)所有用戶的安全,我們要安全加固,除了防火墻還要增加如ips,ids等防病毒入侵檢測設(shè)備對外部數(shù)據(jù)進行分析檢測,確保校園網(wǎng)的安全;
外面做好防護措施,內(nèi)部同樣要做好防護措施,因為有的學(xué)生電腦可能帶回家或者在外面感染,所以內(nèi)部核心交換機上要設(shè)置vlan隔離,旁掛安全設(shè)備對端口進行檢測防護;
內(nèi)網(wǎng)可能有ddos攻擊或者arp病毒等傳播,所以我們要對服務(wù)器或者電腦安裝殺毒軟件,特別是學(xué)校服務(wù)器系統(tǒng)等,安全正版安全軟件,保護重要電腦的安全;
對服務(wù)器本身我們要安全server版系統(tǒng),經(jīng)常修復(fù)漏洞及更新安全軟件,普通電腦一般都是撥號上網(wǎng),如果有異常上層設(shè)備監(jiān)測一般不影響其他電腦。做好安全防范措施,未雨綢繆。
局域網(wǎng)聊天相關(guān)文章: