program.cs

来自「一个用Socket写的客户端及服务器程序」· CS 代码 · 共 53 行

CS
53
字号
//client端
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace socketsample
{
    class Class1
    {
        static void Main()
        {
            try
            {
                int port = 2000;
                string host = "127.0.0.1";
                string sendStr = "";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
                Console.WriteLine("Conneting...");
                c.Connect(ipe);//连接到服务器
                while (sendStr != "close")
                {
                    sendStr = Console.ReadLine();
                    //string sendStr = "hello!This is a socket test";
                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                    Console.WriteLine("Send Message");
                    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("Client Get Message:{0}", recvStr);//显示服务器返回信息
                } 
                c.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?