基本信息
源码名称:即时通信
源码大小:0.04M
文件格式:.rar
开发语言:C#
更新时间:2014-12-27
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
客户端服务器通信

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace ChatClient
{
 class Chat
 {
  public static UdpClient udpClient;
  public static IPEndPoint serverIP;
  public static ChatForm chatForm;
  public static Thread threadReceiveMsg;
       
  public static void start()
  {
   udpClient = new UdpClient(9876);
   serverIP = new IPEndPoint(IPAddress.Parse("172.16.3.51"), 9875);

   chatForm = new ChatForm();
   //chatForm.Show();

   byte[] byteMsg = null;
   byteMsg = Encoding.Default.GetBytes("I");
   udpClient.Send(byteMsg, byteMsg.Length, serverIP);

   threadReceiveMsg = new Thread(new ThreadStart(receiveMsg));
   threadReceiveMsg.IsBackground = true;
   threadReceiveMsg.Start();
  }

  public static void stop()
  {
   byte[] byteMsg = null;
   byteMsg = Encoding.Default.GetBytes("O");
   //udpClient.Send(byteMsg, byteMsg.Length, serverIP);

   threadReceiveMsg.Abort();
  }

  public static void receiveMsg()
  {
   while (true)
   {
    try
    {
     IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
     byte[] recBytes = udpClient.Receive(ref remoteIP);
     if (recBytes == null)
     {
      Thread.Sleep(1000);
      continue;
     }
     chatForm.Show();
     chatForm.showMsg(System.Text.Encoding.Default.GetString(recBytes),remoteIP.Address.ToString());
    }
    catch//(InvalidOperationException)
    {
     Thread.Sleep(3000);
    }
   }
  }

  public static void SendMsg(string msg, string remoteIP)
  {
   byte[] byteMsg = Encoding.Default.GetBytes(msg);
   udpClient.Send(byteMsg, byteMsg.Length, new IPEndPoint(IPAddress.Parse(remoteIP), 9876));
  }
 }
}