Hello.
I don't understand about socket in Windows Phone 7 mango.
My project is sending message from device WP7 to my PC and
sending message from my PC to my WP7.
I found simple code to do it. On PC side using console application, this sample just can send from WP7 to mp PC, in console application there no send() method to send message to WP7.
my question is
1. anyone can help me to modification this code?
2. anyone can modification console application to windows form application?
here the code.
Windows Console Application (PC)
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocketServer
{
static class Program
{
private const char LengthPrefixDelimiter = ';';
private static AutoResetEvent _flipFlop = new AutoResetEvent(false);
static void Main(string[] args)
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList.First(), 22222);
Console.WriteLine("Local address and port : {0}", localEP);
try
{
listener.Bind(localEP);
listener.Listen(1);
while (true)
{
listener.BeginAccept(AcceptCallback, listener);
_flipFlop.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
listener.Accept();
listener.Listen(1);
}
private static void AcceptCallback(IAsyncResult ar)
{
var listener = (Socket)ar.AsyncState;
var socket = listener.EndAccept(ar);
_flipFlop.Set();
var state = new StateObject();
state.Socket = socket;
socket.BeginReceive(state.Buffer,
0,
StateObject.BufferSize,
0,
ReceiveCallback,
state);
}
private static void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket socket = state.Socket;
int read = socket.EndReceive(ar);
bool allRead = true;
if (read > 0)
{
string chunk = Encoding.UTF8.GetString(state.Buffer, 0, read);
state.StringBuilder.Append(chunk);
string messageLengthText = state.StringBuilder.SubstringByDelimiter(LengthPrefixDelimiter);
if (state.TotalSize == 0)
{
if (!string.IsNullOrEmpty(messageLengthText))
{
var messageLength = Convert.ToInt32(messageLengthText);
state.TotalSize = messageLength;
}
else
{
allRead = false;
}
}
allRead = allRead && state.StringBuilder.Length - messageLengthText.Length - 1 == state.TotalSize;
}
if (!allRead)
{
socket.BeginReceive(state.Buffer,
0,
StateObject.BufferSize,
0,
ReceiveCallback,
state);
}
else
{
if (state.StringBuilder.Length > 0)
{
string result = state.StringBuilder.ToString();
result = result.Substring(result.IndexOf(LengthPrefixDelimiter) + 1);
Console.WriteLine("Received a message: {0}", result);
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
public static string SubstringByDelimiter(this StringBuilder sb, char delimiter)
{
StringBuilder result = new StringBuilder(sb.Length);
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == delimiter)
{
return result.ToString();
}
result.Append(sb[i]);
}
return string.Empty;
}
}
public class StateObject
{
public Socket Socket;
public StringBuilder StringBuilder = new StringBuilder();
public const int BufferSize = 10;
public byte[] Buffer = new byte[BufferSize];
public int TotalSize;
}
}
And here on WP7 mango Code
XAML :
<!--
<Grid x:Name="LayoutRoot" removed="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="SOCKET SAMPLE" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Send a msg" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBlock Text="Host:" />
<TextBox x:Name="Host"
HorizontalAlignment="Stretch"
Text="192.168.2.62:22222" />
<TextBlock Text="Message:" />
<TextBox x:Name="Message"
HorizontalAlignment="Stretch" />
<Button x:Name="SendButton"
Content="Send"
Click="SendButton_Click" />
<TextBlock x:Name="ReceivedText" />
</StackPanel>
</Grid>
</Grid>
C# CODE:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using Microsoft.Phone.Controls;
namespace WP7MangoSocketsTest
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void SendButton_Click(object sender, RoutedEventArgs e)
{
var remoteEndpoint = Host.Text;
if (string.IsNullOrEmpty(remoteEndpoint) || remoteEndpoint.IndexOf(':') < 0)
{
return;
}
string[] remoteEndpointParts = remoteEndpoint.Split(':');
string host = remoteEndpointParts[0].Trim();
int port = Convert.ToInt32(remoteEndpointParts[1].Trim());
var ipAddress = IPAddress.Parse(host);
var endpoint = new IPEndPoint(ipAddress, port);
var message = string.Format("{0};{1}", Message.Text.Length, Message.Text);
var buffer = Encoding.UTF8.GetBytes(message);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endpoint;
args.Completed += SocketAsyncEventArgs_Completed;
args.SetBuffer(buffer, 0, buffer.Length);
var socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
bool completesAsynchronously = socket.ConnectAsync(args);
if (!completesAsynchronously)
{
SocketAsyncEventArgs_Completed(args.ConnectSocket, args);
}
}
private void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Error during socket operation: "
+ e.SocketError));
CleanUp(e);
return;
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
HandleConnect(e);
break;
case SocketAsyncOperation.Send:
HandleSend(e);
break;
}
}
private void HandleConnect(SocketAsyncEventArgs e)
{
if (e.ConnectSocket != null)
{
bool completesAsynchronously = e.ConnectSocket.SendAsync(e);
if (!completesAsynchronously)
{
SocketAsyncEventArgs_Completed(e.ConnectSocket, e);
}
}
}
private void HandleSend(SocketAsyncEventArgs e)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Sending successful!"));
CleanUp(e);
}
private void CleanUp(SocketAsyncEventArgs e)
{
if (e.ConnectSocket != null)
{
e.ConnectSocket.Shutdown(SocketShutdown.Both);
e.ConnectSocket.Close();
}
}
}
}
PLEASE HELP ME :D