打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
利用Tcp和socket实现的客户端与服务端的简单通信

/*服务端*/

using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ChatSever
{       class Sever
    {
        static void Main(string[] args)
        {
            Hashtable clientTable = new Hashtable();//存放连接的转发表            
            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];//返回主机的ip地址
            int port=9999;
            int maxsize=1024;
            TcpListener listener = new TcpListener(ip, port);
            listener.Start();
            Console.WriteLine("服务器已启动,正在监听....../n");
            Console.WriteLine(string.Format("服务器IP:{0}/t端口号:{1}/n",ip,port));
            while (true)
            {
              byte[] packetBuff=new byte[maxsize];
              Socket newClient = listener.AcceptSocket();
              newClient.Receive(packetBuff);
              string userName = Encoding.Unicode.GetString(packetBuff).TrimEnd('/0');
              if (clientTable.Count != 0 && clientTable.ContainsKey(userName))//验证是否为唯一用户
              {
                  newClient.Send(Encoding.Unicode.GetBytes("Failed"));
                  continue;
              }
              else
              {
                  newClient.Send(Encoding.Unicode.GetBytes("Successful"));

              }
            //将新的连接加入转发表并创建线程为其服务
              clientTable.Add(userName,newClient);
              string strlog = string.Format("[系统消息]用户{0}在{1}连接.... 当前在线人数:{2}/r/n/r/n",userName ,DateTime.Now ,clientTable.Count);
               Console.WriteLine(strlog);
               Thread thread = new Thread(new ParameterizedThreadStart(Sever.ThreadFunc));
               thread.Start(userName);
               //向所有客户端发送系统消息
               foreach (DictionaryEntry de in clientTable)
               {
                   string clientName = de.Key as string;
                   Socket clientSkt = de.Value as Socket;
                   if (!clientName.Equals(userName))
                   {
                       clientSkt.Send(Encoding.Unicode.GetBytes(strlog));
                   }
               }
            }
        }

        static  void ThreadFunc(object obj)
        {
           //代码----启动新的线程监听来自客户端的信息     

        }
    }
}

/*客户端:*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace CustomProgram
{
    class Custom
    {
        static void Main(string[] args)
        {
          byte [] data=new byte[1024];
          Socket newClient = new Socket(AddressFamily.InterNetwork ,SocketType.Stream,ProtocolType.Tcp);
          Console.WriteLine("请输入服务器的地址:");
          string ipadd = Console.ReadLine();
          Console.WriteLine("请输入服务的端口号:");
           int  port = Convert.ToInt32(Console.ReadLine());
          IPEndPoint ipend = new IPEndPoint(IPAddress .Parse(ipadd) ,port);
          try
          {
              newClient.Connect(ipend);//连接服务器;
          }
          catch(SocketException e)
          {
              Console.WriteLine("连接服务器失败!");
              Console.WriteLine(e.Message);
              return;
          }
          int rec = newClient.Receive(data);
          string stringdata = Encoding.ASCII.GetString(data,0,rec);
          Console.WriteLine(stringdata);
          while (true)
          {
              string input = Console.ReadLine();
              if (input.ToUpper() == "EXIT")
                  break;
              newClient.Send(Encoding.ASCII .GetBytes(input));
              data =new byte[1024];
              rec = newClient.Receive(data);
              stringdata = Encoding.ASCII.GetString(data,0,rec);
              Console.WriteLine("{0}来自服务器消息:{1}",DateTime.Now,stringdata);
          }
          Console.WriteLine("断开连接!");
          newClient.Shutdown(SocketShutdown.Both);
          newClient.Close();
         }
    }
}

一上完成之后,右击项目解决方案的属性把项目设为多启动,同时运行客户端与服务端即可;

希望这个实例能对刚学C#网络编程的人有所帮助吧,小弟水平很菜,有不对的地方还请论坛里的大侠给小弟指正!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# TCP Socket通信客户端
C# Socket编程笔记
JSON.NET与ProtoBuf在Socket下的应用
Socket 同步和异步模式
写一个简易web服务器、ASP.NET核心知识(4)
c#Socket通信实例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服