C# NetworkStream 实例:

服务器端:

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

namespace Server
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";   
        static void Main(string[] args)
        {
            //监听指定IP地址和端口
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            Console.WriteLine("Listening...");
            listener.Start();

            //进来的客户端连接
            TcpClient client = listener.AcceptTcpClient();
            //通过流获取进来的数据
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //读取进来的流
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
            //接收的数据转换成字符串
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received :" + dataReceived);

            //给客户端写回文本
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);

            client.Close();
            listener.Stop();
            Console.ReadLine();


        }
    }
}

客户端:

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

namespace Console_Clict_netWork
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";
        static void Main(string[] args)
        {
            //字符串发送到服务器
            string textToSend = DateTime.Now.ToString();

            //在IP和端口上,建立一个TCPClient对象
            TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //发送文本
            Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //读回文本
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);

            Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
            Console.ReadLine();

            client.Close();
        }
    }
}

 

posted @ 2013-03-12 17:18  blog_yuan  阅读(425)  评论(0编辑  收藏  举报