基本信息
源码名称:TCP/IP通信客户端与服务端程序
源码大小:0.34M
文件格式:.rar
开发语言:C#
更新时间:2019-04-12
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

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

本次赞助数额为: 2 元 
   源码介绍

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

namespace ServerConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            const int BufferSize = 8192;  //缓存大小,8192字节

            Console.WriteLine("Server is running ...");
            IPAddress iP = new IPAddress(new byte[] {127,0,0,1 });
            TcpListener listener = new TcpListener(iP, 8500);

            listener.Start();  //开始侦听
            Console.WriteLine("Start Listening ...");

            //获取一个连接,同步方法,在此中断
            TcpClient remoteClient = listener.AcceptTcpClient();

            //打印连接到的客户端信息
            Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
    
            //获得流
            NetworkStream streamToClient = remoteClient.GetStream();
            do
            {
                //写入buffer中
                byte[] buffer = new byte[BufferSize];
                int bytesRead;
                try
                {
                    lock (streamToClient)
                    {
                        bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                    }
                    if (bytesRead == 0)
                        throw new Exception("读取到0字节。");
                    Console.WriteLine("Reading data, {0} bytes ...", bytesRead);

                    //获得请求的字符串
                    string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Receieve: {0}", msg);

                    //转换成大写并发送
                    msg = msg.ToUpper();
                    buffer = Encoding.Unicode.GetBytes(msg);
                    lock (streamToClient)
                    {
                        streamToClient.Write(buffer, 0, buffer.Length);
                    }
                    Console.WriteLine("Sent: {0}", msg);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
            } while (true);

            streamToClient.Dispose();
            remoteClient.Close();

            //按Q退出
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
        }
    }
}