当前位置:编程学习 > C#/ASP.NET >>

关于这段代码如何退出程序

各位达达,下面这个程序是一个非常简单的C#聊天程序,基于UDP协议,我的本意是通过最后输入QUIT退出这个程序,在调试的时候也发现确实退出到了Main的最一个的花括号,但是程序还是感觉就那样死了,再也不动了,以下是源码:要同时在本机上运行两个程序才可以演示这个聊天的效果,请达人出来解答一下如何退出这个程序!


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

namespace ChatApp
{
    class Chat
    {
        private static IPAddress remoteIPAddress;
        private static int remotePort;
        private static int localPort;

        [STAThread]
        static void Main(string[] args)
        {

            try
            {
                // Get necessary data for connection 
                Console.WriteLine("Enter Local Port");
                localPort = Convert.ToInt16(Console.ReadLine());

                Console.WriteLine("Enter Remote Port");
                remotePort = Convert.ToInt16(Console.ReadLine());

                //Console.WriteLine("Enter Remote IP address");
                //remoteIPAddress = IPAddress.Parse(Console.ReadLine());
                remoteIPAddress = IPAddress.Parse("127.0.0.1");


                // Create thread for listening 
                Thread tRec = new Thread(new ThreadStart(Receiver));
                tRec.Start();

                while (true)
                {
                    string strValue = Console.ReadLine();
                    if (strValue.ToUpper() == "QUIT")
                    {
                        if (tRec.ThreadState != ThreadState.Stopped)
                            tRec.Abort();
                        break;
                    }
                    else
                    {
                        Send(strValue);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("Press any key to return");
            Console.Read();
        }

        private static void Send(string datagram)
        {
            // Create UdpClient 
            UdpClient sender = new UdpClient();

            // Create IPEndPoint with details of remote host 
            IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort);

            try
            {
                // Convert data to byte array 
                byte[] bytes = Encoding.ASCII.GetBytes(datagram);

                // Send data 
                sender.Send(bytes, bytes.Length, endPoint);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close connection 
                sender.Close();
            }
        }

        public static void Receiver()
        {
            // Create a UdpClient for reading incoming data, 
            UdpClient receivingUdpClient = new UdpClient(localPort);

            // IPEndPoint with remote host information 
            IPEndPoint RemoteIpEndPoint = null;

            try
            {
                Console.WriteLine(
                           "-----------*******Ready for chat!!!*******-----------");

                while (true)
                {
                    // Wait for datagram 
                    byte[] receiveBytes = receivingUdpClient.Receive(
                                                               ref RemoteIpEndPoint);

                    // Convert and display data 
                    string returnData = Encoding.ASCII.GetString(receiveBytes);

                    Console.WriteLine("-" + returnData.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
--------------------编程问答-------------------- up --------------------编程问答-------------------- 等待达达出来解决问题 --------------------编程问答-------------------- 这是客户端的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace client
{
    class class1
    {
        static void Main()
        {
           
           
                try
                {
                    int port = 2000;
                    string host = "127.0.0.1";
                    IPAddress ip = IPAddress.Parse(host);
                    IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
                    Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
                   
                    c.Connect(ipe);//连接到服务器
                    string sendStr = Console.ReadLine();
                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                   
                    c.Send(bs, bs.Length, 0);//发送测试信息
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                    Console.WriteLine("用户2:\n{0}\n用户1:", recvStr);//显示服务器返回信息
                    c.Close();
                    Main();
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException:{0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException:{0}", e);
                }
               
                Console.ReadLine();
            }
        }
    }



这是服务器端的代码:

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace sever
{
    class Class2
    {
        static void Main()
        {
           
                try
                {
                    int port = 2000;
                    string host = "127.0.0.1";
                    IPAddress ip = IPAddress.Parse(host);
                    IPEndPoint ipe = new IPEndPoint(ip, port);
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
                    s.Bind(ipe);//绑定2000端口
                    s.Listen(0);//开始监听
                   
                    Socket temp = s.Accept();//为新建连接创建新的Socket。
                   
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                    Console.WriteLine("用户1:\n{0}\n用户2:", recvStr);//把客户端传来的信息显示出来
                    string sendStr =Console .ReadLine ();
                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                    temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                    temp.Close();
                    s.Close();
                    Main();
                }
           
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException:{0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException:{0}", e);
                }
               
                Console.ReadLine();
            }
        }
    }

你既然问的是C#,那你电脑上应该按得有vs2005或者vs2008吧,先让服务器端运行,再让客户端运行,就能实现qq聊天功能。 当其中任一端断开时对方就会有提示:另一方已经断开。 试一下吧!
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,