socket 实现 Windows Phone 7 即时聊天(二)
本文是对http://www.cnblogs.com/shit/archive/2012/04/11/2441737.html的改进。
新增内容:增加一个控制台通过模拟wp7客户端进行客户端间的聊天互动
好像上个版本有中文问题,这个版本没有,手机可以接收到中文正常显示。
服务器采用中间转发,通过分词识别发送信息。
控制台sever
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 { /// <summary> /// 保存连接的所有用户 /// </summary> static private List<User> userList = new List<User>(); //static Socket clientSocket=null; //Socket serverSocket = null; static void Main(string[] args) { Console.WriteLine("----------------------windows phone7 socket server------------------------"); IPEndPoint id = new IPEndPoint(IPAddress.Parse("59.73.204.208"), 8888); //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 { Socket clientSocket = null; User user = new User();// (clientSocket); //在套接字上接收接入的连接 user.client = serverSocket.Accept(); //开一个线程处理 Thread clientThread = new Thread(ReceiveData); clientThread.Start(user); userList.Add(user); } catch (Exception ex) { } } } private static void ReceiveData(object userState) { User user = (User)userState; Socket clientSocket = user.client; //状态 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 = "欢迎使用芒果微博客户端即时聊天,您已登录成功"; 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.UTF8.GetString(buffer).Substring(0, bufLen); string[] splitString = clientcommand.Split(','); switch (splitString[0]) { case "Login": user.userName = splitString[1]; Console.WriteLine(user.userName+"上线了"); AsyncSendToAllClient(clientcommand); // AsyncSendToAllClient(user, clientcommand); break; case "Logout": // AsyncSendToAllClient(user, clientcommand); // RemoveUser(user); return; case "Talk": string talkString = clientcommand.Substring(splitString[0].Length + splitString[1].Length + 2); // AddItemToListBox(string.Format("{0}对{1}说:{2}", user.userName, splitString[1], talkString)); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "Talk," + user.userName + "," + talkString); break; } } break; default: break; } } } /// <summary> /// 异步发送message给user /// </summary> /// <param name="user"></param> /// <param name="message"></param> static private void AsyncSendToClient(User user, string message) { byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes(message); user.client.Send(data, data.Length, SocketFlags.None); } /// <summary> /// 异步发送message给所有user /// </summary> /// <param name="user"></param> /// <param name="message"></param> static private void AsyncSendToAllClient( string message) { byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes(message); foreach (User target in userList) { target.client.Send(data, data.Length, SocketFlags.None); } } } class User { public Socket client { get; set; } public string userName { get; set; } public User()//Socket client) { // this.client = client; } public void Close() { client.Close(); } } }
控制台client
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; namespace ConsoleApplication2 { class Program { static Socket s = null; /// <summary> /// 枚举状态字 /// </summary> enum ClientStatus : byte { Connecting, Connected, Receiving, Received, Shutting, Shutted } /// <summary> /// clientStatus 表示当前连接状态 /// </summary> static ClientStatus clientStatus = ClientStatus.Shutted; static ManualResetEvent done = new ManualResetEvent(false); static void Main(string[] args) { bool retVal = EstablishTCPConnection("59.73.204.208", int.Parse("8888")); //bool retVal = EstablishTCPConnection("222.27.111.87", int.Parse("8888")); } static 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) { Console.WriteLine("连接超时请重试! " + e.SocketError); } else if (e.SocketError == SocketError.ConnectionRefused) { Console.WriteLine("服务器端问启动" + e.SocketError); } else { Console.WriteLine("出错了" + e.SocketError); } } else { //连接成功 开启一个线程循环接收消息 Thread th = new Thread(new ThreadStart(Receive)); th.Start(); //添加服务器到在线列表 // Dispatcher.BeginInvoke(() => onlinelist.Items.Add(" 小i")); byte[] data = new byte[1024]; Thread clientThread = new Thread(new ThreadStart(delegate() { while (true) { var newMessage = Console.KeyAvailable ? Console.ReadLine() : null; if (newMessage != null) { data = Encoding.UTF8.GetBytes(newMessage); s.Send(data, data.Length, SocketFlags.None); } } })); clientThread.Start(); } done.Set(); }); done.Reset(); s.ConnectAsync(socketEventArg); clientStatus = ClientStatus.Connecting; return done.WaitOne(10000); } 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> static 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); string clientcommand = received; string[] splitString = clientcommand.Split(','); switch (splitString[0]) { case "Login": //user.userName = splitString[1]; Console.WriteLine(splitString[1] + "上线了"); // AsyncSendToAllClient(user, clientcommand); break; case "Logout": // AsyncSendToAllClient(user, clientcommand); // RemoveUser(user); return; case "Talk": string talkString = clientcommand.Substring(splitString[0].Length + splitString[1].Length + 2); // AddItemToListBox(string.Format("{0}对{1}说:{2}", user.userName, splitString[1], talkString)); Console.WriteLine(splitString[1] + "对你说:" + talkString); break; default: break; } // MessageBox.Show(received); // Console.WriteLine(" 小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; } } } } } }
wp7的内容更改 主要是分词
/// 发送消息 /// </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); Dispatcher.BeginInvoke(() =>{ // chatlistbox.Items.Add(" 我:" + data); string[] splitString = data.Split(','); if (splitString[0] == "Talk") { showmsg(data.Substring(splitString[0].Length + splitString[1].Length + 2), true); chatlistbox.ScrollIntoView(chatlistbox.Items[chatlistbox.Items.Count - 1]); } }); return done.WaitOne(10000); } return false; } /// <summary> /// 循环接收消息 /// </summary> public void Receive() { Send("Login," + "zhuo"); 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)); string clientcommand = received; string[] splitString = clientcommand.Split(','); switch (splitString[0]) { case "Login": //user.userName = splitString[1]; Dispatcher.BeginInvoke(() => { MessageBox.Show(splitString[1] + "上线了"); onlinelist.Items.Add(splitString[1]); }); // AsyncSendToAllClient(user, clientcommand); break; case "Logout": // AsyncSendToAllClient(user, clientcommand); // RemoveUser(user); break; case "Talk": string talkString = clientcommand.Substring(splitString[0].Length + splitString[1].Length + 2); // AddItemToListBox(string.Format("{0}对{1}说:{2}", user.userName, splitString[1], talkString)); Dispatcher.BeginInvoke(() => { // chatlistbox.Items.Add(splitString[1] + ":" + talkString); showmsg(talkString, false); chatlistbox.ScrollIntoView(chatlistbox.Items[chatlistbox.Items.Count - 1]); }); break; default: //Dispatcher.BeginInvoke(() => chatlistbox.Items.Add(received)); break; } } } } 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; } } } }
做了很久的东西一直没有机会发上来,希望对你们有帮助。