zoukankan      html  css  js  c++  java
  • socket实现Windows Phone 7即时聊天

    本例实现一个简单的控制台与wp7端的聊天对话。采用多线程处理接入的客户端。代码都贴上来吧。注释写的很明白了应该。传下图:

    xaml文件:

     <Grid x:Name="LayoutRoot" Background="#FF3399FF">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
    
            <!--TitlePanel contains the name of the application and page title-->
            <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
                <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
                <TextBlock x:Name="PageTitle" FontSize="45" Text="chat with server" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
            </StackPanel>
    
            <!--ContentPanel - place additional content here-->
            <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
                <TextBox Height="72" HorizontalAlignment="Left" Margin="30,463,0,0" Name="textBoxTextToSend" Text="" VerticalAlignment="Top" Width="393" Background="White" BorderBrush="White" BorderThickness="1" />
                <Button Content="Send" Height="72" HorizontalAlignment="Left" Margin="223,526,0,0" Name="buttonSend" VerticalAlignment="Top" Width="160" Click="buttonSend_Click" />
                <ListBox Height="451" HorizontalAlignment="Left" Margin="30,6,0,0" Name="chatlistbox"  VerticalAlignment="Top" Width="395" Background="#E5FFFFFF" Foreground="#FF020700" FontStretch="Normal" />
                <Button Content="Online list" Height="72" HorizontalAlignment="Left" Margin="30,526,0,0" Name="button1" VerticalAlignment="Top" Width="173" Click="button1_Click" />
                <ListBox Background="White" FontStretch="Normal" Foreground="#FF020700" Height="451" HorizontalAlignment="Left" Margin="30,10,0,0" Name="onlinelist"  VerticalAlignment="Top" Width="393" SelectionChanged="onlinelist_SelectionChanged" />
            </Grid>
        </Grid>
    

    wp7 cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Microsoft.Phone.Controls;
    using System.Net.Sockets;
    using System.Threading;
    using System.Text;
    namespace WeiboSdkSample.PageViews
    {
        public partial class chat : PhoneApplicationPage
        {
            Socket s = null;
            /// <summary>
            /// 枚举状态字
            /// </summary>
            enum ClientStatus : byte
            {
                Connecting, Connected, Receiving, Received, Shutting, Shutted
            } 
            /// <summary>
            /// clientStatus 表示当前连接状态
            /// </summary>
            ClientStatus clientStatus = ClientStatus.Shutted;
            static ManualResetEvent done = new ManualResetEvent(false);
             public chat()
            {
                InitializeComponent();
                bool retVal=EstablishTCPConnection("222.27.111.87", int.Parse("8888"));
            }
            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void buttonSend_Click(object sender, RoutedEventArgs e)
            {
                Send(textBoxTextToSend.Text);
            }
            /// <summary>
            /// 连接服务器
            /// </summary>
            /// <param name="host"></param>
            /// <param name="port"></param>
            /// <returns></returns>
            public bool EstablishTCPConnection(string host, int port)
            {
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = new DnsEndPoint(host, port);
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
                {
                    if (e.SocketError != SocketError.Success)
                    {
    
                        if (e.SocketError == SocketError.ConnectionAborted)
                        {
                            Dispatcher.BeginInvoke(() => MessageBox.Show("连接超时请重试! " + e.SocketError));
                        }
                        else if (e.SocketError == SocketError.ConnectionRefused)
                        {
                            Dispatcher.BeginInvoke(() => MessageBox.Show("服务器端问启动" + e.SocketError));
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() => MessageBox.Show("出错了" + e.SocketError));
                        }
                    }
                    else
                    {
                        //连接成功 开启一个线程循环接收消息
                        Thread th = new Thread(new ThreadStart(Receive));
                        th.Start();
                        //添加服务器到在线列表
                        Dispatcher.BeginInvoke(() => onlinelist.Items.Add("  小i"));
                    }
                    done.Set();
    
                });
                done.Reset();
                s.ConnectAsync(socketEventArg);
                clientStatus = ClientStatus.Connecting;
                return done.WaitOne(10000);
            }
            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public bool Send(string data)
            {
                if (s != null)
                {
                    SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                    socketEventArg.RemoteEndPoint = s.RemoteEndPoint;
                    socketEventArg.UserToken = null;
    
                    socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
                    {
                        done.Set();
                    });
    
                    socketEventArg.SetBuffer(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                    done.Reset();
                    s.SendAsync(socketEventArg);
                    chatlistbox.Items.Add(" 我:" + data);
                    return done.WaitOne(10000);
                }
                return false;
            }
            /// <summary>
            /// 循环接收消息
            /// </summary>
            public void Receive()
            {
                string received = "";
                var socketReceiveArgs = new SocketAsyncEventArgs();
                while (clientStatus != ClientStatus.Shutted)
                {
                    switch (clientStatus)
                    {
                        case ClientStatus.Connecting:
                            {
                                socketReceiveArgs.SetBuffer(new byte[512], 0, 512);
                                socketReceiveArgs.Completed += delegate(object sender1, SocketAsyncEventArgs receiveArgs)
                                {
                                    if (receiveArgs.SocketError == SocketError.Success)
                                    {
    
                                        if (clientStatus != ClientStatus.Shutting)
                                        {
                                            if (receiveArgs.BytesTransferred == 0)
                                                clientStatus = ClientStatus.Shutting;
                                            else
                                            {
                                                clientStatus = ClientStatus.Received;
                                                received = Encoding.UTF8.GetString(receiveArgs.Buffer, receiveArgs.Offset, receiveArgs.BytesTransferred);
                                               // MessageBox.Show(received);
                                                Dispatcher.BeginInvoke(() => chatlistbox.Items.Add(" 小i:" + received));
    
                                               
                                            }
                                        }
                                    }
                                    else
                                        clientStatus = ClientStatus.Shutting;
                                };
                                clientStatus = ClientStatus.Receiving;
                                s.ReceiveAsync(socketReceiveArgs);
    
                                break;
                            }
                        case ClientStatus.Received:
                            {
                                clientStatus = ClientStatus.Receiving;
                                s.ReceiveAsync(socketReceiveArgs);
                                break;
                            }
                        case ClientStatus.Shutting:
                            {
                                s.Close();
                                clientStatus = ClientStatus.Shutted;
                                break;
                            }
                    }
                }
            }
            public void CloseSocket()
            {
                if (s != null)
                {
                    s.Close();
                }
            }
            /// <summary>
            /// 这个listbox在线列表是项目需要加加上来的,你们删掉吧。。
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void onlinelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                onlinelist.Visibility = Visibility.Collapsed;
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                onlinelist.Visibility = onlinelist.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
            }
        }
    }

    控制台:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static Socket clientSocket=null;
            Socket serverSocket = null;
            static void Main(string[] args)
            {
                Console.WriteLine("----------------------windows phone7 socket server------------------------");
                IPEndPoint id = new IPEndPoint(IPAddress.Parse("222.27.111.87"), 8888);
                Console.WriteLine("local address:"+id.Address+"Port:"+id.Port);
                Console.WriteLine("---input message and press enter to send your message to all client--- ");
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(id);
                serverSocket.Listen(10);
                while (true)
                 {
                    try
                     {
                        //在套接字上接收接入的连接
                        clientSocket = serverSocket.Accept();
                        //开一个线程处理
                        Thread clientThread = new Thread(new ThreadStart(ReceiveData));
                        clientThread.Start();
                }
                catch (Exception ex)
                 {
                }
            }
    
        }
        private static void ReceiveData()
            {
               //状态
               bool keepalive = true;
               Socket s = clientSocket;
               Byte[] buffer = new Byte[1024];
               //根据收听到的客户端套接字向客户端发送信息
               IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
               Console.WriteLine("Client:" + clientep.Address + "("+clientep.Port+")"+"上线了");
               string welcome = "欢迎使用XXX,您已登录成功";
               byte[] data = new byte[1024];
               data = Encoding.UTF8.GetBytes(welcome);
               s.Send(data, data.Length, SocketFlags.None);
               //开启新线程处理用户输入 换行后发送消息
               Thread clientThread = new Thread(new ThreadStart(delegate (){
                   while (keepalive)
                   {
                       var newMessage = Console.KeyAvailable ? Console.ReadLine() : null;
                       if (newMessage != null)
                       {
                           data = Encoding.UTF8.GetBytes(newMessage); 
                           s.Send(data, data.Length, SocketFlags.None);
                       }
                   }
               })); clientThread.Start();
               while (keepalive)
                {
                   //在套接字上接收客户端发送的信息
                   int bufLen = 0;
                   try
                    {
                       bufLen = s.Available;
                       s.Receive(buffer, 0, bufLen, SocketFlags.None);
                       if (bufLen == 0)
                           continue;
                   }
                   catch (Exception ex)
                    {
                       Console.WriteLine("Client:" + clientep.Address + "(" + clientep.Port + ")" + "下线了");
                       keepalive = false;
                       return;
                   }
                   clientep = (IPEndPoint)s.RemoteEndPoint;
                   string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);
                   Console.WriteLine("wp7:"+clientcommand);
               }
    }
        }
    }

    仓促作品,不善之处 ,望请指教

    本博客地址http://www.cnblogs.com/shit

  • 相关阅读:
    angularjs的$on、$emit、$broadcast
    angularjs中的路由介绍详解 ui-route(转)
    ionic入门教程-ionic路由详解(state、route、resolve)(转)
    Cocos Creator 加载使用protobuf第三方库,因为加载顺序报错
    Cocos Creator 计时器错误 cc.Scheduler: Illegal target which doesn't have uuid or instanceId.
    Cocos Creator 构造函数传参警告 Can not instantiate CCClass 'Test' with arguments.
    Cocos Creator 对象池NodePool
    Cocos Creator 坐标系 (convertToWorldSpaceAR、convertToNodeSpaceAR)
    Cocos Creator 常驻节点addPersistRootNode
    Cocos Creator 配合Tiled地图的使用
  • 原文地址:https://www.cnblogs.com/shit/p/2441737.html
Copyright © 2011-2022 走看看