关于UDP连接的问题

genelin22 2007-08-09 09:33:54
写了个客户端,连不上(服务器端没问题),主要代码如下

byte[] incomingbuf = new byte[1<<16];
System.Diagnostics.Debug.WriteLine("connecting to port " + _port);
try
{
_socket = new System.Net.Sockets.UdpClient(60001);
_socket.Connect("192.168.2.2", 10011);
String str="connection request";
byte[] buf = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray());
int count = _socket.Send(buf,buf.Length);
System.Diagnostics.Debug.WriteLine(_port + ": send a string with the count=" + count);
System.Net.IPEndPoint ipendpoint = null;
incommingbuf = _socket.Receive(ref ipendpoint);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~在这收不到东西了
System.Diagnostics.Debug.WriteLine(_port + ": connected");
_isConnected = true;
}
catch
{
System.Diagnostics.Debug.WriteLine(_port + ":catched an exception while connecting");
}
用java写了个同样的东西 却能收到东西,代码如下
byte[] incomingbuf = new byte[1<<16];
DatagramPacket incoming = new DatagramPacket(incomingbuf,incomingbuf.length);
try
{
_socket=new DatagramSocket();
_socket.connect(InetAddress.getByName(“192.168.2.2”), 10011);
String buf="connection request";
DatagramPacket message = new DatagramPacket(buf, buf.length);
_socket.send(message);
incomingbuf.length);

_socket.setSoTimeout(500);
_socket.receive(incoming);
//~~~~~~~~~~~~~~~~~~~可以正常收到数据包
_socket.setSoTimeout(0); //set to be blocking
System.out.println("["+_port+"] connected ");
_isConnected=true;
} catch (Exception ex) {}

哪位高手指点一下可能是什么原因吧,急!
谢谢 :)
...全文
174 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
n112339 2008-09-01
  • 打赏
  • 举报
回复
定下就好了
zpingy 2007-09-06
  • 打赏
  • 举报
回复
呵呵,luyangph() 看得真切,引用对象不能为空
zpingy 2007-09-04
  • 打赏
  • 举报
回复
用异步的方式,或者开线程。
luyangph 2007-09-04
  • 打赏
  • 举报
回复
System.Net.IPEndPoint ipendpoint = null;
incommingbuf = _socket.Receive(ref ipendpoint);
注意这两句
不应为null
luyangph 2007-09-04
  • 打赏
  • 举报
回复
System.Net.IPEndPoint ipendpoint = null;
incommingbuf = _socket.Receive(ref ipendpoint);
注意这两句
不就为null
nacarat 2007-08-09
  • 打赏
  • 举报
回复
1.udp协议无须连接
2.incommingbuf = _socket.Receive(ref ipendpoint); 参数 ipendpoint 为空

//
IPEndPoint rep= new IPEndPoint(你的主机IP,端口号);
Byte[] receiveBytes = receivingUdpClient.Receive(ref rep);
godgreat 2007-08-09
  • 打赏
  • 举报
回复
沙发,帮忙顶
genelin22 2007-08-09
  • 打赏
  • 举报
回复
不好意思 java代码部分错了 更正如下
byte[] incomingbuf = new byte[1<<16];
DatagramPacket incoming = new DatagramPacket(incomingbuf,incomingbuf.length);
try
{
_socket=new DatagramSocket();
_socket.connect(InetAddress.getByName(“192.168.2.2”), 10011);

byte[] buf = (new String("connection request")).getBytes();
DatagramPacket message = new DatagramPacket(buf, buf.length);
_socket.send(message);

_socket.setSoTimeout(500);
_socket.receive(incoming);
//~~~~~~~~~~~~~~~~~~~可以正常收到数据包
_socket.setSoTimeout(0); //set to be blocking
System.out.println("["+_port+"] connected ");
_isConnected=true;
} catch (Exception ex) {}

110,567

社区成员

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

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

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