本例實現一個簡單的控制台與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); } } } }
倉促作品,不善之處 ,望請指教
