关于C#发送和接收的问题!

fengforever 2004-08-25 03:52:46
private void Btn_Submit_Click(object sender, System.EventArgs e)
{
UdpClient client = new System.Net.Sockets.UdpClient("127.0.0.1",11006);
byte[] ms = null;
ms = Encoding.Default.GetBytes(this.TB_Send.Text);
int x = client.Send(ms,ms.Length);
MessageBox.Show("Send "+x+" bytes","Alert");

UdpClient receivingUdpClient = new System.Net.Sockets.UdpClient("127.0.0.1",11006);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any,11000);
try
{
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.Default.GetString(receiveBytes);
this.TB_Recieve.Text = returnData;
}
catch
{

}
}
...全文
123 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fengforever 2004-08-29
  • 打赏
  • 举报
回复
我现在弄不清楚的,就是
写一个接收的程序,怎么把它加到进程里运行
然后一直监听某一个端口的通讯呢?
速马 2004-08-26
  • 打赏
  • 举报
回复
同步模式,又不是多线程,就容易出这种诡异的问题唔
outer2000 2004-08-26
  • 打赏
  • 举报
回复
而且是同步的,阻塞了,设置一个超时什么的
outer2000 2004-08-26
  • 打赏
  • 举报
回复
你这样看来是不可以,因为UDP你发送完后就丢失了;你需要写两个程序,一个先接着;
然后另一个再发;
fengforever 2004-08-26
  • 打赏
  • 举报
回复
没有人吗?
fengforever 2004-08-25
  • 打赏
  • 举报
回复
其实我对这个很不了解
我把发送和接收都写在一个程序文件中
这样做可以吗?
如果不行,需要怎么写呢?
谢谢
werdcd 2004-08-25
  • 打赏
  • 举报
回复
这是tcp的,希望对你有帮助……
werdcd 2004-08-25
  • 打赏
  • 举报
回复
m_Socket = new TcpClient( "61.139.72.194" , m_nPort ) ;
//MessageBox.Show("成功连接到服务器!");
string temp = this.sendMsg("login#"+user_id+"#"+machine_id+"#"+user_pwd+"%");//收发函数
/// <summary>
/// 向服务器传输信息,同时收到服务器返回的信息
/// </summary>
private string sendMsg( string msg )
{
NetworkStream stream = null ;
Byte[] data = System.Text.Encoding.ASCII.GetBytes( msg );
try
{
Debug.Write(msg);
stream = m_Socket.GetStream();
stream.Write(data, 0, data.Length);
stream.Flush() ;
}
catch( SocketException e )
{
Debug.Write( "SocketException: " + e.ToString() );
return null ;
}

Thread.Sleep( 300 ) ;

Byte[] data1 = new byte[128] ;

try
{
stream.Read( data1 , 0 , data1.Length ) ;
string rcv = System.Text.Encoding.ASCII.GetString( data1 ) ;
stream.Flush();
return rcv.ToString().Trim();
}
catch( Exception ex )
{
Debug.Write( "SocketException: " + ex.Message.ToString() );
return null ;
}
}
fengforever 2004-08-25
  • 打赏
  • 举报
回复
为什么执行到
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
这里的时候就没有相应了呢?

110,538

社区成员

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

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

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