学习啦>学习电脑>网络知识>网络基础知识>《怎么使用Socket实现局域网聊天》正文

怎么使用Socket实现局域网聊天

时间:2018-10-30 13:58:01本文内容及图片来源于读者投稿,如有侵权请联系xuexila888@qq.com 加城 我要投稿

  局域网通常是分布在一个有限地理范围内的网络系统,一般所涉及的地理范围只有几公里。局域网专用性非常强,具有比较稳定和规范的拓扑结构。这篇文章主要为大家详细介绍了C#使用Socket实现局域网聊天的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

怎么使用Socket实现局域网聊天

  C#代码:

  servlet服务端

  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 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();

  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("")!=-1)

  {

  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.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客户端

  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("
","\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;

  }

  }

  }

  }

  补充:局域网、校园网安全维护方法

  校园网络分为内网和外网,就是说他们可以上学校的内网也可以同时上互联网,大学的学生平时要玩游戏购物,学校本身有自己的服务器需要维护;

  在大环境下,首先在校园网之间及其互联网接入处,需要设置防火墙设备,防止外部攻击,并且要经常更新抵御外来攻击;

  由于要保护校园网所有用户的安全,我们要安全加固,除了防火墙还要增加如ips,ids等防病毒入侵检测设备对外部数据进行分析检测,确保校园网的安全;

  外面做好防护措施,内部同样要做好防护措施,因为有的学生电脑可能带回家或者在外面感染,所以内部核心交换机上要设置vlan隔离,旁挂安全设备对端口进行检测防护;

  内网可能有ddos攻击或者arp病毒等传播,所以我们要对服务器或者电脑安装杀毒软件,特别是学校服务器系统等,安全正版安全软件,保护重要电脑的安全;

  对服务器本身我们要安全server版系统,经常修复漏洞及更新安全软件,普通电脑一般都是拨号上网,如果有异常上层设备监测一般不影响其他电脑。做好安全防范措施,未雨绸缪。


局域网聊天相关文章:

1.局域网下怎么聊天用到什么命令

2.局域网怎样使用微信语音聊天功能

3.不联网局域网内计算机怎么互相聊天

4.局域网微信消息列表在哪

5.局域网微信群聊怎么找

学习啦友链、商务、投稿、客服:QQ:3061683909 邮箱3061683909@qq.com

Copyright @ 2006 - 2020 学习啦 All Rights Reserved

学习啦 版权所有 粤ICP备15032933号-1

我们采用的作品包括内容和图片全部来源于网络用户和读者投稿,我们不确定投稿用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的权利,请联系:xuexila888@qq.com,我站将及时删除。

学习啦

回到顶部