关于客户端向服务端发送信息的一个问题

c_pass 2012-01-04 04:30:39
需求:页面多个按钮,点击其中一个按钮后,就把按钮的id发送给服务端。
目前遇到这个问题:在sending里面如何判断不同的按钮的点击 或者说如何获取到被点击的按钮ID

private void button1_Click(object sender, EventArgs e)
{
IPEndPoint epServer = new IPEndPoint(IPAddress.Parse("192.168.2.23"), 9000);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(epServer, new AsyncCallback(Sending), socket);
}
private void Sending(IAsyncResult rec_socket)
{
Socket socket = (Socket)rec_socket.AsyncState;
try
{
if (socket.Connected)
{
byte[] msgBuff = Encoding.UTF8.GetBytes("点击发送信息1按钮");
socket.Send(msgBuff);
}
else
{
Console.WriteLine("Error!", "Error!");
}
}
catch
{
Console.WriteLine("Error!", "Error!");
}
}

...全文
88 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
stonespace 2012-01-04
  • 打赏
  • 举报
回复
class MyState
{
public Socket rSocket=null;
public int m_nID=-1;
}

private void button1_Click(object sender, EventArgs e)
{
IPEndPoint epServer = new IPEndPoint(IPAddress.Parse("192.168.2.23"), 9000);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MyState rState=new MyState();
rState.rSocket=socket;
rState.m_nID=你要传递的ID;
socket.BeginConnect(epServer, new AsyncCallback(Sending), rState);
}
private void Sending(IAsyncResult rec_socket)
{
MyState rState= rec_socket.AsyncState as MyState ;
Socket socket = rState.rSocket;
try
{
if (socket.Connected)
{
byte[] msgBuff = Encoding.UTF8.GetBytes("点击发送信息"+rState.m_nID.ToString()+"按钮");
socket.Send(msgBuff);
}
else
{
Console.WriteLine("Error!", "Error!");
}
}
catch
{
Console.WriteLine("Error!", "Error!");
}
}

c_pass 2012-01-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 stonespace 的回复:]
标准的实现方法:

rec_socket.AsyncState不要直接放socket,你可以写一个结构体,放在socket.BeginConnect的第三个参数,这样rec_socket.AsyncState可以获得这个结构体,

这个结构体中一个成员放socket,其他的按钮id等可以放在结构体的其他成员中传递到sending,
[/Quote]
抱歉 实在不会 能不能稍微给点提示
c_pass 2012-01-04
  • 打赏
  • 举报
回复
好的 我尝试写下这个类
stonespace 2012-01-04
  • 打赏
  • 举报
回复
说错了,应该不是结构体,应该是一个类,
stonespace 2012-01-04
  • 打赏
  • 举报
回复
标准的实现方法:

rec_socket.AsyncState不要直接放socket,你可以写一个结构体,放在socket.BeginConnect的第三个参数,这样rec_socket.AsyncState可以获得这个结构体,

这个结构体中一个成员放socket,其他的按钮id等可以放在结构体的其他成员中传递到sending,

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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