silverlight的socket,怎么样,实现再连接?

vincevincevincevince 2010-08-26 11:11:45
public partial class Chat : UserControl
{
SynchronizationContext synChat;
System.Net.Sockets.Socket socketChat;
SocketAsyncEventArgs socketArgsChat = new SocketAsyncEventArgs();

public static string arr;
//世界聊天
public static string world;
//全部
public static string contents = "0";

static int i = 1;
Contents ct = new Contents();
public Chat()
{
InitializeComponent();
socketChat = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketArgsChat.RemoteEndPoint = new DnsEndPoint("192.168.1.11", 4506);
socketArgsChat.Completed += new EventHandler<SocketAsyncEventArgs>(socketArgsChat_Completed);
socketChat.ConnectAsync(socketArgsChat);





}

public void OnSendChat(string a)
{
byte[] bytes = Encoding.UTF8.GetBytes(a);
synChat = SynchronizationContext.Current;
socketArgsChat.UserToken = bytes;
socketChat.ConnectAsync(socketArgsChat); //??




}
void socketArgsChat_Completed(object sender, SocketAsyncEventArgs e)
{
//当任何一个Socket动作完成,都回调该函数,然后对LastOperation进行判断后继续执行相应的部分

switch (e.LastOperation)
{

case SocketAsyncOperation.Connect:

ProcessConnectChat(e);

break;

case SocketAsyncOperation.Receive:

ProcessReceiveChat(e);

break;

case SocketAsyncOperation.Send:

ProcessSendChat(e);

break;

}
}
void ProcessReceiveChat(SocketAsyncEventArgs e)
{

synChat.Post(GetTextChat, Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length) + " and Received");
}



private void OutPutText(string content)
{
//在聊天文本框中输出指定的信息,并将滚动条滚到底部
this.Dispatcher.BeginInvoke(
delegate
{
TextBlock tb = new TextBlock() { TextWrapping = TextWrapping.Wrap };

//if (_localIPAndPort == msg.SenderIPAndPort)
//{
// tb.Inlines.Add("我 ");
//}
//else
//{
// tb.Inlines.Add(msg.SenderName + " ");
//}
tb.Inlines.Add(Home.userName);
tb.Inlines.Add(new Run() { Text = DateTime.Now.ToString(), Foreground = new SolidColorBrush(Colors.Gray) });


// tb.Inlines.Add(" 对 " + msg.ReceiverName + " 说:");



tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new Run() { Text = content });

lstChat.Items.Add(tb);

}
);
}


void ProcessConnectChat(SocketAsyncEventArgs e)
{



//当连接成功后,获取Socket参数 e传递过来的用户标识(也就是本示例中用户输入的字符串转换的Byte字节数组)

byte[] bytes = (byte[])e.UserToken;



//设置Socket参数的缓冲区参数,将我们的字节数组设置为Socket的缓冲区。

e.SetBuffer(bytes, 0, bytes.Length);



//同步一下上下文,显示一下当前的状态信息。

// syn.Post(GetText, "States:" + e.SocketError.ToString() + "," + e.LastOperation.ToString());



//发送数据

socketChat.SendAsync(e);



}



//发送完成后,执行等待接收服务器发回的数据

void ProcessSendChat(SocketAsyncEventArgs e)
{

//定义个空的字节数组,设置好其大小

byte[] bytes = new byte[1024];

//将前面定义字节数组设置成缓冲区

e.SetBuffer(bytes, 0, bytes.Length);

//执行异步接收

socketChat.ReceiveAsync(e);

}




public void Split()
{

//arr = adduser + "|" + countryid + "|" + userID + "|" + armygroupid + "|" + userName;
arr = adduser + "|" + Home.countryid + "|" + Home.userID + "|" + "0" + "|" + Home.userName;

}


public void GetTextChat(object str)
{
// 获取到服务端信息了
}

在下面的一句中,我想问这里面。如果服务端有信息,怎么样再获取到信息?就像在下面调用_socket.ReceiveAsync(e);,不过,提示SocketAsyncEventArgs 已使用。怎么改?
void ProcessReceiveChat(SocketAsyncEventArgs e)
{

synChat.Post(GetTextChat, Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length) + " and Received");
// 继续异步地从服务端 Socket 接收数据
_socket.ReceiveAsync(e);
}


...全文
179 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jv9 2010-08-29
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 vincevincevincevince 的回复:]
怎么引入这个方法
public void OnSendChat(string a)
{
byte[] bytes = Encoding.UTF8.GetBytes(a);
synChat = SynchronizationContext.Current;
socketArgsChat.UserToken = bytes;
socketChat.ConnectAsy……
[/Quote]

可以作为抽象类实现,创建公用类库,可以供不同于页面和类调用。
  • 打赏
  • 举报
回复
怎么引入这个方法
public void OnSendChat(string a)
{
byte[] bytes = Encoding.UTF8.GetBytes(a);
synChat = SynchronizationContext.Current;
socketArgsChat.UserToken = bytes;
socketChat.ConnectAsync(socketArgsChat); //??

}
而且在不同页面,不同类可以调用
jv9 2010-08-28
  • 打赏
  • 举报
回复
请参考:


public class Example
{
static ManualResetEvent clientDone = new ManualResetEvent(false);

public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{

SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
DnsEndPoint hostEntry = new DnsEndPoint("http://www.contoso.com", 80);

// Create a socket and connect to the server
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed);

socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.UserToken = sock;
sock.ConnectAsync(socketEventArg);
clientDone.WaitOne();
}

// A single callback is used for all socket operations.
// This method forwards execution on to the correct handler
// based on the type of completed operation
static void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
ProcessConnect(e);
break;
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new Exception("Invalid operation completed");
}
}

// Called when a ConnectAsync operation completes
private static void ProcessConnect(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Successfully connected to the server

// Send 'Hello World' to the server
byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
e.SetBuffer(buffer, 0, buffer.Length);
Socket sock = e.UserToken as Socket;
bool willRaiseEvent = sock.SendAsync(e);
if (!willRaiseEvent)
{
ProcessSend(e);
}
}
else
{
throw new SocketException((int)e.SocketError);
}
}

// Called when a ReceiveAsync operation completes
// </summary>
private static void ProcessReceive(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Received data from server

// Data has now been sent and received from the server.
// Disconnect from the server
Socket sock = e.UserToken as Socket;
sock.Shutdown(SocketShutdown.Send);
sock.Close();
clientDone.Set();
}
else
{
throw new SocketException((int)e.SocketError);
}
}


// Called when a SendAsync operation completes
private static void ProcessSend(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Sent "Hello World" to the server successfully

//Read data sent from the server
Socket sock = e.UserToken as Socket;
bool willRaiseEvent = sock.ReceiveAsync(e);
if (!willRaiseEvent)
{
ProcessReceive(e);
}
}
else
{
throw new SocketException((int)e.SocketError);
}
}
}


  • 打赏
  • 举报
回复
没人回答,自己顶一下

8,736

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧