C#--TCP实例(实现了client)

如果你耐得住寂寞,这个聊天软件你可以玩一年

这是客户端的代码:

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

//添加新的命名空间  
using System.Net;
using System.Net.Sockets;
using System.IO;              //流StreamReader  
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)
            {
                //通过clientSocket接收数据  
                int receiveLength = clientSocket.Receive(result);
                Console.WriteLine("接收服务器消息:/n   {0}", Encoding.ASCII.GetString(result, 0, receiveLength));
                string ss = "console:/n   "+Console.ReadLine();
                clientSocket.Send(Encoding.ASCII.GetBytes(ss));
            }
        }
    }
}  

然后我就调用这个:
这里写图片描述

作为tcp的服务器,就可以一起聊天了哈哈哈

猜你喜欢

转载自blog.csdn.net/qq_27262241/article/details/53740605