//服务端

//前端

<Window x:Class="WpfApp_TCPIPServer.TServerWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TServerWindow" Height="350" Width="525">
    <Grid>
        <Label Content="输入:" HorizontalAlignment="Left" Height="38" Margin="20,234,0,0" VerticalAlignment="Top" Width="73"/>
        <TextBox x:Name="txtMsg" HorizontalAlignment="Left" Height="75" Margin="98,234,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="215"/>
        <Button Click="btnSend_Click" Content="发送" HorizontalAlignment="Left" Height="38" Margin="401,256,0,0" VerticalAlignment="Top" Width="92"/>
        <Border Margin="10,85,24,90" BorderThickness="3" BorderBrush="#FFF31A1A"  >
            <TextBlock x:Name="txtInfo" HorizontalAlignment="Left"     TextWrapping="Wrap"   VerticalAlignment="Top" Margin="0,-3,-3,-3" Width="480" Height="144"  />
        </Border>

        <Label Content="IP:" HorizontalAlignment="Left" Height="27" Margin="10,10,0,0" VerticalAlignment="Top" Width="57"/>
        <TextBox x:Name="iPTxt" Text="192.168.100.10" HorizontalAlignment="Left" Height="27" Margin="83,10,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="118"/>
        <Label Content="端口:" HorizontalAlignment="Left" Height="27" Margin="220,10,0,0" VerticalAlignment="Top" Width="48"/>
        <TextBox x:Name="portTxt" Text="5000" HorizontalAlignment="Left" Height="27" Margin="289,10,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="72"/>
        <Button Content="开始侦听" HorizontalAlignment="Left" Height="27" Margin="397,10,0,0" VerticalAlignment="Top" Width="84" Click="Button_Click"/>

    </Grid>
</Window>
View Code

 

//后台

  1 namespace WpfApp_TCPIPServer
  2 {
  3     /// <summary>
  4     /// TServerWindow.xaml 的交互逻辑
  5     /// </summary>
  6     public partial class TServerWindow : Window
  7     {
  8         public TServerWindow()
  9         {
 10             InitializeComponent();
 11         }
 12 
 13         //public List<TcpClient> Clients = new List<TcpClient>();  //客户端列表  
 14 
 15         private TcpListener tcpListener;//侦听对象
 16         private NetworkStream networkStream;//数据传输对象
 17 
 18 
 19         //开始监听
 20         private void Button_Click(object sender, RoutedEventArgs e)
 21         {
 22             IPAddress ip = IPAddress.Parse(iPTxt.Text);
 23             int port = int.Parse(portTxt.Text);
 24 
 25             try
 26             {
 27                 tcpListener = new TcpListener(ip, port); //初始化侦听连接
 28                 tcpListener.Start();//启动侦听
 29                 ShowMsg("服务器开始侦听");
 30 
 31 
 32                 //1.异步
 33                 //tcpListener.BeginAcceptTcpClient(new AsyncCallback(ClientAccept), tcpListener);//异步接收传入的连接操作
 34 
 35 
 36                 //2.同步,使用后台线程
 37                 Thread thread = new Thread(Connect);
 38                 thread.IsBackground = true;
 39                 thread.Start();
 40             }
 41             catch (Exception ex)
 42             {
 43                 ShowMsg(ex.Message);
 44 
 45             }
 46 
 47         }
 48 
 49 
 50         //接收
 51         private void Connect(object obj)
 52         {
 53             byte[] b = new byte[1024];
 54             string str = null;
 55             while (true)
 56             {
 57                 ShowMsg("Waiting for a connection... ");
 58                 TcpClient tClient = tcpListener.AcceptTcpClient(); //接收挂起的连接请求
 59                 ShowMsg("建立连接");
 60                 str = null;
 61                 networkStream = tClient.GetStream();
 62                 int i;
 63                 while ((i = networkStream.Read(b, 0, b.Length)) != 0)
 64                 {
 65                     str = Encoding.UTF8.GetString(b, 0, i);
 66                     ShowMsg("receive:" + str);
 67                     //byte[] b2 = Encoding.UTF8.GetBytes(str);
 68                     //networkStream.Write(b2, 0, b2.Length);
 69                     //ShowMsg("send:" + str);
 70                 }
 71                 tClient.Close();
 72             }
 73         }
 74         //发送
 75         private void Send(string str)
 76         {
 77             byte[] b2 = Encoding.UTF8.GetBytes(str);
 78             networkStream.Write(b2, 0, b2.Length);
 79             ShowMsg("send:" + str);
 80         }
 81 
 82 
 83 
 84 
 85 
 86         /// <summary>
 87         /// 接收连接的回调函数
 88         /// </summary>
 89         /// <param name="ar"></param>
 90         private void ClientAccept(IAsyncResult ar)
 91         {
 92             TcpListener tcpLst = (TcpListener)ar.AsyncState;
 93 
 94             TcpClient Tcpclt = tcpLst.EndAcceptTcpClient(ar);//异步接受传入的连接尝试,并创建新的TCPClient处理远程连接通信
 95             //获取客户端的ip和port
 96             string clientIP = ((IPEndPoint)Tcpclt.Client.RemoteEndPoint).Address.ToString();
 97             int clientPort = ((IPEndPoint)Tcpclt.Client.RemoteEndPoint).Port;
 98             //获取数据传输对象
 99             networkStream = Tcpclt.GetStream();
100             byte[] data = new byte[1024 * 1024];
101             networkStream.BeginRead(data, 0, data.Length, new AsyncCallback(DataRec), data);//启动数据侦听
102         }
103 
104         /// <summary>
105         /// 接收数据
106         /// </summary>
107         /// <param name="ar"></param>
108         private void DataRec(IAsyncResult ar)
109         {
110             try
111             {
112                 int length = networkStream.EndRead(ar);
113                 List<byte> list = new List<byte>();
114                 list.AddRange((byte[])ar.AsyncState);
115                 list.RemoveRange(length, list.Count - length);//移除多余部分
116                 string msgStr = Encoding.UTF8.GetString(list.ToArray());
117                 ShowMsg("B:" + msgStr);
118 
119                 byte[] data2 = new byte[1024 * 1024];
120                 networkStream.BeginRead(data2, 0, data2.Length, new AsyncCallback(DataRec), data2);
121 
122             }
123             catch (Exception ex)
124             {
125                 ShowMsg(ex.Message);
126             }
127         }
128 
129         StringBuilder sb = new StringBuilder();
130         private void ShowMsg(string msg)
131         {
132             sb.Append(msg + "\r\n");
133             Dispatcher.Invoke(new Action(() => { txtInfo.Text = sb.ToString(); }));
134 
135         }
136 
137         //发送消息
138         private void btnSend_Click(object sender, RoutedEventArgs e)
139         {
140             byte[] data = Encoding.UTF8.GetBytes(txtMsg.Text.ToString());
141 
142             if (networkStream != null)
143             {
144                 networkStream.Write(data, 0, data.Length);//向服务器发送数据
145 
146                 ShowMsg(txtMsg.Text.ToString());
147             }
148         }
149 
150 
151 
152     }
153 }

 

//客户端

//前端

<Window x:Class="WpfApp_TCPIP.TClientWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TClientWindow" Height="350" Width="525">
    <Grid>
        <Label Content="输入:" HorizontalAlignment="Left" Height="33" Margin="23,253,0,0" VerticalAlignment="Top" Width="60"/>
        <TextBox x:Name="txtMsg" HorizontalAlignment="Left" Height="56" Margin="83,253,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="221"/>
        <Button Content="发送"   HorizontalAlignment="Left" Height="33" Margin="369,253,0,0" VerticalAlignment="Top" Width="95" Click="Button_Click"/>
        <Border BorderBrush="Green" BorderThickness="3" Margin="23,68,53,112">
            <TextBlock x:Name="txtInfo" Margin="0,-3,0,0"></TextBlock>
        </Border>
        <Label Content="IP:" HorizontalAlignment="Left" Height="27" Margin="10,10,0,0" VerticalAlignment="Top" Width="57"/>
        <TextBox x:Name="iPTxt" Text="192.168.100.10" HorizontalAlignment="Left" Height="27" Margin="83,10,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="118"/>
        <Label Content="端口:" HorizontalAlignment="Left" Height="27" Margin="220,10,0,0" VerticalAlignment="Top" Width="48"/>
        <TextBox x:Name="portTxt" Text="5000" HorizontalAlignment="Left" Height="27" Margin="289,10,0,0" TextWrapping="Wrap"   VerticalAlignment="Top" Width="72"/>
        <Button Content="连接" HorizontalAlignment="Left" Height="27" Margin="397,10,0,0" VerticalAlignment="Top" Width="84" Click="Button_Click_1"/>

    </Grid>
</Window>
View Code

 

//后台

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp_TCPIP
{
    /// <summary>
    /// TClientWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TClientWindow : Window
    {
        public TClientWindow()
        {
            InitializeComponent();
        }


        private TcpClient tcpClient;
        private NetworkStream networkStream;//数据流

        //建立连接
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            IPAddress ip = IPAddress.Parse(iPTxt.Text);
            int port = int.Parse(portTxt.Text);

            try
            {
                tcpClient = new TcpClient();
                networkStream = null;
                tcpClient.BeginConnect(ip, port, new AsyncCallback(Connect), tcpClient);

                //ShowMsg("连接成功");
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);

            }


        }


        /// <summary>
        /// 建立连接的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void Connect(IAsyncResult ar)
        {
            TcpClient TcpClt = (TcpClient)ar.AsyncState;//将传递的参数强制转换成TCPClient
            if (TcpClt.Connected)
            {
                ShowMsg("连接成功");
                networkStream = TcpClt.GetStream();//获取数据流传输对象
                byte[] data = new byte[1024*1024];//新建传输的缓冲;
                networkStream.BeginRead(data, 0, data.Length, new AsyncCallback(DataRec), data);//异步接收数据
            }
            else
            {
                ShowMsg("连接失败");
            }

        }

        /// <summary>
        /// 数据接收委托函数
        /// </summary>
        /// <param name="ar"></param>
        private void DataRec(IAsyncResult ar)
        {
            try
            {
                int length = networkStream.EndRead(ar);//处理异步读取的结束,返回读取的字节数长度
                List<byte> list = new List<byte>();
                list.AddRange((byte[])ar.AsyncState);
                list.RemoveRange(length, list.Count - length);//移除多余部分
                string msgStr = Encoding.UTF8.GetString(list.ToArray());
                ShowMsg("A:" + msgStr);

                List<byte> dataList = new List<byte>();
                dataList.AddRange((byte[])ar.AsyncState);//获取数据


                dataList.RemoveRange(length, dataList.Count - length);//根据长度移除无效的数据
                byte[] data2 = new byte[1024*1024];//重新定义接收缓冲
                networkStream.BeginRead(data2, 0, data2.Length, new AsyncCallback(DataRec), data2);//重新挂起异步等待
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }

        }


        StringBuilder sb = new StringBuilder();
        private void ShowMsg(string msg)
        {
            sb.Append(msg + "\r\n");
            Dispatcher.Invoke(new Action(() => { txtInfo.Text = sb.ToString(); }));

        }


        //发送消息
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            byte[] data = Encoding.UTF8.GetBytes(txtMsg.Text.ToString());

            if (networkStream != null)
            {
                networkStream.Write(data, 0, data.Length);//向服务器发送数据

                ShowMsg(txtMsg.Text.ToString());
            }
        }
    }
}
View Code

 

posted on 2018-03-13 13:55  逛园子$$$  阅读(561)  评论(0)    收藏  举报