[求助]socket.send发送数据无法接收

gong_max 2011-06-22 05:41:48
下面是我的代码,发送数据后,客户端接收不到。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SocketServer
{
class Program
{
private static int PORT = 8888;

static void Main(string[] args)
{
Socket ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(ip,PORT);
ss.Bind(ep);
ss.Listen(3);
Console.WriteLine("开始监听");
while (true)
{
Socket s = ss.Accept();
Console.WriteLine("监听到新连接");
Boolean b = true;
while (b)
{
try
{
Byte[] rb = new byte[64];
int len = s.Receive(rb);
for (int i = 0; i < len; i++)
{
Console.Write(string.Format("{0:X2}", rb[i]));
}
Console.WriteLine();
byte[] bytes = new byte[8];
bytes[0] = 1;
bytes[1] = Convert.ToByte('0');
bytes[2] = Convert.ToByte('1');
bytes[3] = 0;
bytes[4] = 8;
bytes[5] = 0;
bytes[6] = 0;
bytes[7] = 0;
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(string.Format("{0:X2}", bytes[i]));
}
Console.WriteLine();
s.Send(bytes, bytes.Length,0);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
s.Close();
b = false;
}
finally
{
}
}
}
}
}
}

send语法是没错的,我如何查看数据是否真正的发送出去了。
...全文
63 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
gong_max 2011-06-27
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 gclol 的回复:]

我不明白没有NetworkStream你怎么发送数据,我都是用NetworkStream的Write和Read方法去读写数据,你这段代码能不能用
C# code

IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
TcpListener myServer = new TcpListener(……
[/Quote]
流的底层也是send和read,只不过.net把它封装成立一个流,用起来更加方便。
gclol 2011-06-22
  • 打赏
  • 举报
回复
我不明白没有NetworkStream你怎么发送数据,我都是用NetworkStream的Write和Read方法去读写数据,你这段代码能不能用

IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
TcpListener myServer = new TcpListener(ipAddress, 65000);
myServer.Start();
for (; ; )
{
Socket mySocket = myServer.AcceptSocket();
NetworkStream ns = new NetworkStream(mySocket);
byte[] buffer = new byte[100];
ns.Read(buffer, 0, buffer.Length);
string str = Encoding.ASCII.GetString(buffer);
Console.WriteLine(str);
}
PBGong 2011-06-22
  • 打赏
  • 举报
回复
代码没有错误!!
gong_max 2011-06-22
  • 打赏
  • 举报
回复
抱歉,给大家添麻烦了。代码是正确的,服务端的问题,还是对别人写的东东迷信了

110,538

社区成员

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

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

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