sl2.0中引入socket对象,在网上找到一段代码,然后配合一个服务器代码,可以使用:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 4522;//端口
IPAddress localAddr = IPAddress.Parse("10.24.189.207");//服务器的ip地址
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
客户端代码:
SocketClient sc = new SocketClient("10.24.189.207", 80);
sc.Connect();
string z = sc.SendReceive("test");
this.ScTxt.Text = z;// System.Windows.Application.Current.Host.Source.Host;
其中 SocketClient 是一个辅助类,来自网上的:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace System.Prolight.SilverSocket
{
internal sealed class SocketClient : IDisposable
{
private const int Receive = 1;
private const int Send = 0;
private bool isConnected = false;
private Socket socket;
private DnsEndPoint endPoint;
private IPEndPoint z;
private static AutoResetEvent autoEvent = new AutoResetEvent(false);
private static AutoResetEvent[] autoSendReceiveEvents = new AutoResetEvent[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
internal SocketClient(string host, int port)
{
z = new IPEndPoint(IPAddress.Parse(host), port);
endPoint = new DnsEndPoint(host, port);
socket = new Socket(AddressFamily.InterNetwork
/* hostEndPoint.AddressFamily */,
SocketType.Stream, ProtocolType.Tcp);
}
internal void Connect()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.UserToken = socket;
args.RemoteEndPoint = z;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
socket.ConnectAsync(args);
autoEvent.WaitOne();
if (args.SocketError != SocketError.Success)
throw new SocketException((int)args.SocketError);
}
internal void Disconnect()
{
socket.Close();
}
#region Events
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
autoEvent.Set();
isConnected = (e.SocketError == SocketError.Success);
}
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
autoSendReceiveEvents[Send].Set();
}
private void OnSend(object sender, SocketAsyncEventArgs e)
{
autoSendReceiveEvents[Receive].Set();
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Send)
{
// Prepare receiving.
Socket s = e.UserToken as Socket;
byte[] response = new byte[255];
e.SetBuffer(response, 0, response.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
s.ReceiveAsync(e);
}
}
else
{
ProcessError(e);
}
}
#endregion
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (s.Connected)
s.Close();
}
}
throw new SocketException((int)e.SocketError);
}
internal String SendReceive(string message)
{
if (isConnected)
{
Byte[] bytes = Encoding.UTF8.GetBytes(message);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(bytes, 0, bytes.Length);
args.UserToken = socket;
args.RemoteEndPoint = endPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
socket.SendAsync(args);
AutoResetEvent.WaitAll(autoSendReceiveEvents);
return Encoding.UTF8.GetString(args.Buffer, args.Offset, args.BytesTransferred);
}
else
throw new SocketException((int)SocketError.NotConnected);
}
#region IDisposable Members
public void Dispose()
{
autoEvent.Close();
autoSendReceiveEvents[Send].Close();
autoSendReceiveEvents[Receive].Close();
if (socket.Connected)
socket.Close();
}
#endregion
}
}
先运行服务器,然后在其他机器上访问服务器上的sl,注意我的主机地址是“10.24.189.207”,你们修改成自己的,或者使用System.Windows.Application.Current.Host.Source.Host 来处理。
服务器显示 test,客户端显示"TEST".
代码下载
https://files.cnblogs.com/songsgroup/SilverLightSocket.rar
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 4522;//端口
IPAddress localAddr = IPAddress.Parse("10.24.189.207");//服务器的ip地址
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
客户端代码:
SocketClient sc = new SocketClient("10.24.189.207", 80);
sc.Connect();
string z = sc.SendReceive("test");
this.ScTxt.Text = z;// System.Windows.Application.Current.Host.Source.Host;
其中 SocketClient 是一个辅助类,来自网上的:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace System.Prolight.SilverSocket
{
internal sealed class SocketClient : IDisposable
{
private const int Receive = 1;
private const int Send = 0;
private bool isConnected = false;
private Socket socket;
private DnsEndPoint endPoint;
private IPEndPoint z;
private static AutoResetEvent autoEvent = new AutoResetEvent(false);
private static AutoResetEvent[] autoSendReceiveEvents = new AutoResetEvent[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
internal SocketClient(string host, int port)
{
z = new IPEndPoint(IPAddress.Parse(host), port);
endPoint = new DnsEndPoint(host, port);
socket = new Socket(AddressFamily.InterNetwork
/* hostEndPoint.AddressFamily */,
SocketType.Stream, ProtocolType.Tcp);
}
internal void Connect()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.UserToken = socket;
args.RemoteEndPoint = z;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
socket.ConnectAsync(args);
autoEvent.WaitOne();
if (args.SocketError != SocketError.Success)
throw new SocketException((int)args.SocketError);
}
internal void Disconnect()
{
socket.Close();
}
#region Events
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
autoEvent.Set();
isConnected = (e.SocketError == SocketError.Success);
}
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
autoSendReceiveEvents[Send].Set();
}
private void OnSend(object sender, SocketAsyncEventArgs e)
{
autoSendReceiveEvents[Receive].Set();
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Send)
{
// Prepare receiving.
Socket s = e.UserToken as Socket;
byte[] response = new byte[255];
e.SetBuffer(response, 0, response.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
s.ReceiveAsync(e);
}
}
else
{
ProcessError(e);
}
}
#endregion
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (s.Connected)
s.Close();
}
}
throw new SocketException((int)e.SocketError);
}
internal String SendReceive(string message)
{
if (isConnected)
{
Byte[] bytes = Encoding.UTF8.GetBytes(message);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(bytes, 0, bytes.Length);
args.UserToken = socket;
args.RemoteEndPoint = endPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
socket.SendAsync(args);
AutoResetEvent.WaitAll(autoSendReceiveEvents);
return Encoding.UTF8.GetString(args.Buffer, args.Offset, args.BytesTransferred);
}
else
throw new SocketException((int)SocketError.NotConnected);
}
#region IDisposable Members
public void Dispose()
{
autoEvent.Close();
autoSendReceiveEvents[Send].Close();
autoSendReceiveEvents[Receive].Close();
if (socket.Connected)
socket.Close();
}
#endregion
}
}
先运行服务器,然后在其他机器上访问服务器上的sl,注意我的主机地址是“10.24.189.207”,你们修改成自己的,或者使用System.Windows.Application.Current.Host.Source.Host 来处理。
服务器显示 test,客户端显示"TEST".
代码下载
https://files.cnblogs.com/songsgroup/SilverLightSocket.rar