C#中Socket编程解决应用程序直接的通信

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

客户端:

namespace SocketClient
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static void Main(string[] args)
        {

//设定服务器IP地址  
              IPAddress ip = IPAddress.Parse("127.0.0.1"); 
              Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
              try 
              { 
                  clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口  
                  Console.WriteLine("连接服务器成功"); 
              } 
              catch 
              { 
                  Console.WriteLine("连接服务器失败,请按回车键退出!");
                  return;
              }

//while (true)
              //{
                  try
                  {
                      Thread.Sleep(1000);    //等待1秒钟 
                      //通过clientSocket接收数据  
                      int receiveLength = clientSocket.Receive(result);
                      Console.WriteLine("接收来自服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
                      Console.ReadKey();
                  }
                  catch
                  {
                      clientSocket.Shutdown(SocketShutdown.Both);
                      clientSocket.Close();
                     // break;
                  }
              //}
                 /*   //通过 clientSocket 发送数据  
              for (int i = 0; i < 10; i++) 
              { 
                  try 
                  { 
                      Thread.Sleep(1000);    //等待1秒钟  
                      string sendMessage = "client send Message Hellp" + DateTime.Now; 
                      clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage)); 
                      Console.WriteLine("向服务器发送消息:{0}" + sendMessage); 
                  } 
                  catch 
                  { 
                      clientSocket.Shutdown(SocketShutdown.Both); 
                      clientSocket.Close(); 
                      break; 
                  } 
              } 
              Console.WriteLine("发送完毕,按回车键退出"); 
               Console.ReadLine(); 
*/

}
    }
}

服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SocketServer
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8885;   //端口  
        static Socket serverSocket; 
        static void Main(string[] args)
        {
            //服务器IP地址  
            IPAddress ip = IPAddress.Parse(IPAddress.Loopback.ToString());//即:"127.0.0.1"
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口  
            serverSocket.Listen(10);    //设定最多10个排队连接请求  
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());

Socket clientSocket = serverSocket.Accept();

while (true)
            {
                Thread.Sleep(1000);    //等待1秒钟

string sendMessage = "Server Say Hello";
                //
                if (!clientSocket.Poll(10,SelectMode.SelectRead))
                {
                int t = clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                Console.WriteLine("服务器向监听到的客服端 发送信息:{0}" + sendMessage);
                }else{
                    Console.WriteLine("客户端已断开连接,");
                    break;
                }
               
                //  Thread receiveThread = new Thread(ReceiveMessage);
                //   receiveThread.Start(clientSocket);
            }
            Console.ReadKey();
            //通过Clientsoket发送数据  
        //    Thread myThread = new Thread(ListenClientConnect);
       //     myThread.Start();
         //   Console.ReadLine();

}

/// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();

string sendMessage = "Server Say Hello";

clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                
                Console.WriteLine("向客服端 发送消息:{0}" + sendMessage); 
              //  Thread receiveThread = new Thread(ReceiveMessage);
             //   receiveThread.Start(clientSocket);
            }
        }

/// <summary>  
        /// 接收消息  
        /// </summary>  
        /// <param name="clientSocket"></param>  
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据  
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        } 
    }
}

上一篇:Node.js + Web Socket 打造即时聊天程序嗨聊


下一篇:Linux登录出现modle is unknow