UDP问题!
udp client端代码:class QClient1
{
[STAThread]
static void Main(string[] args)
{
args = new string[3];
args[0] = "202.×××.×××.×××";
args[1] = "60000";
args[2] = "0";
//判断命令行是否准确,应当是:
//服务器IP 端口(60000) 选项(0或1) [姓名](如果选项为1)
if(args.GetLength(0)!=3&&args.GetLength(0)!=4)
{
Console.WriteLine("参数错误!");
return;
}
QClient1 qClient=new QClient1();
//记录服务端IP和端口
string strHost=args[0];
ushort uiPort=Convert.ToUInt16(args[1]);
String command;
//生成通信指令字符串
if(args.GetLength(0)==3)
command="GET "+args[2];
else
command="GET "+args[2]+" "+args[3];
Console.WriteLine ( "initializing client..." );
//
Console.WriteLine ( "connecting to " + strHost + ":" +
uiPort + "..." );
// 连接到服务端
try
{
qClient.client = new UdpClient (60001 );
}
catch
{
Console.WriteLine("不能连接到服务端!");
return;
}
//
string result;
Console.WriteLine ( command);
//获得本地IP地址
string strLocal=System.Net.Dns.GetHostName();
ushort uiLocalPort=60001;
//组装新的命令
string command1=strHost+":"+uiLocalPort.ToString()+":"+command;
Byte[] cmd = System.Text.Encoding.ASCII.GetBytes (
command1.ToCharArray () );
//发送请求通信指令
qClient.client.Send(cmd,cmd.Length,strHost,uiPort);
// get response
Console.WriteLine ("Result is:");
while(true)
{
//接收结果
IPEndPoint dummy = null;
byte[] res = qClient.client.Receive ( ref dummy );
result = System.Text.Encoding.ASCII.GetString(res);
if(result.Equals("\r\n"))
break;
Console.WriteLine ( result );
}
Console.WriteLine ( "\nclosing connection..." );
//断开连接
qClient.client.Close ();
Console.Write ( "press return to exit" );
Console.ReadLine ();
}
//TCP客户端对象
private UdpClient client = null;
}
}
udp SEVERB 端代码
static void Main(string[] args)
{
QServer1 qServer=new QServer1();
Console.WriteLine ( "initializing server..." );
//创建UDP,并与端口60000绑定,开始侦听
UdpClient server;
try
{
server = new UdpClient ( 60000 );
}
catch
{
Console.WriteLine("创建监听端口失败!");
return;
}
bool loop = true;
IPEndPoint dummy = null;
//服务端一旦起动,就进入监听循环中,不退出。虽然,
//由于没有创建单独的线程来处理用户连接,
//不能支持并发的客户访问,但支持用户多次访问和不同用户的顺序访问。
while ( loop )
{
Console.WriteLine ( "waiting for request..." );
//接收数据
byte[] tmp = server.Receive ( ref dummy );
string dg =new System.Text.ASCIIEncoding ().GetString (tmp );
string[] cmd = dg.Split ( new Char[] {':'} );
string remoteClientHost = cmd[0];
int remoteClientPort = Int32.Parse ( cmd[1] );
string command = cmd[2];
char split=' ';
String [] strRec;
//解析命令字符:strRec[0]应当是GET strRec[1]应当为0或1
//如果strRec[1]为1,则
//strRec[2]为学生的姓名
strRec=command.Split(split);
int parameternum=strRec.GetLength(0);
strRec[0]=strRec[0].ToUpper();
//分析命令有效性,及把请求数据发回客户端
if(strRec[0].Equals("GET"))
{
if(strRec[1].Equals("0"))
{
for(int i=0;i<qServer.strName.GetLength(0);i++)
{
String str=qServer.strName[i]+
" "+qServer.strGrade[i]+"\r\n";
Byte[] res = System.Text.Encoding.ASCII.
GetBytes(str.ToCharArray());
server.Send ( res, res.Length, remoteClientHost,
remoteClientPort );
}
}
else if(strRec[1].Equals("1"))
{
if(strRec.GetLength(0)!=3)
{
String str="The Command is Error,not include Name"+"\r\n";
Byte[] res = System.Text.Encoding.ASCII.
GetBytes(str.ToCharArray());
server.Send ( res, res.Length, remoteClientHost,
remoteClientPort );
}
else
{
int i;
for(i=0;i<qServer.strName.GetLength(0);i++)
{
strRec[2]=strRec[2].Trim();
qServer.strName[i]=qServer.strName[i].Trim();
if(qServer.strName[i].Equals(strRec[2]))
{
String str=qServer.strName[i]+
" "+qServer.strGrade[i]+"\r\n";
Byte[] res = System.Text.Encoding.ASCII.
GetBytes(str.ToCharArray());
server.Send ( res, res.Length, remoteClientHost,
remoteClientPort );
break;
}
}
if(i==qServer.strName.GetLength(0))
{
String str="The Name is not find"+"\r\n";
Byte[] res = System.Text.Encoding.ASCII.
GetBytes(str.ToCharArray());
server.Send ( res, res.Length, remoteClientHost,
remoteClientPort );
}
}
}
else
{
String str="The Command is Error,Head is "+strRec[0]+
",is should be GET"+"\r\n";
Byte[] res = System.Text.Encoding.ASCII.
GetBytes(str.ToCharArray());
server.Send ( res, res.Length, remoteClientHost,
remoteClientPort );
Console.WriteLine("The Command is Error,Head is {0},is should be GET",strRec[0]);
}
}
//处理完后发一个空行,客户端依此来确定,数据接收完毕。必须有,
//否则客户端不会退出。
String str1="\r\n";
Byte[] res1 = System.Text.Encoding.ASCII.
GetBytes(str1.ToCharArray());
server.Send ( res1, res1.Length, remoteClientHost,
remoteClientPort );
}
}
//二个数组用来存储学生姓名和成绩。这里为了示例,比较简单,
//实际使用时,应当用数据库来替代。
//注意二个数组的大小一定要一致。
public string []strName={"qiugufeng","qiuyuanfeng","xiaoli ","xiaowang "};
public string []strGrade={"100","90","95","80" };
}
我在服务器上运行sever端程序,在我的本机上运行client代码,为什么一运行client代码,服务器端程序就报错,而且client没有得到相应?
--------------------编程问答-------------------- 帮顶 --------------------编程问答-------------------- 应该是一连接就报错吧?可能是你的客户端程序在请求服务器连接的时候发送消息的格式有问题 --------------------编程问答--------------------
可是在本机上测试是没有问题的啊 --------------------编程问答-------------------- 顶起来! --------------------编程问答-------------------- 类似下边这种语句我不知道你在什么地方看来的
IPEndPoint dummy = null;
byte[] res = qClient.client.Receive ( ref dummy );
result = System.Text.Encoding.ASCII.GetString(res);
我查找.net帮助信息好像和你的使用方法很大不同
从绑定的 Socket 套接字接收数据,将数据存入接收缓冲区。
命名空间:System.Net.Sockets
程序集:System(在 system.dll 中)
public int Receive (
byte[] buffer
)
public static int SendReceiveTest1(Socket server)
{
byte[] msg = Encoding.UTF8.GetBytes("This is a test");
byte[] bytes = new byte[256];
try
{
// Blocks until send returns.
int i = server.Send(msg);
Console.WriteLine("Sent {0} bytes.", i);
// Get reply from the server.
i = server.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
catch (SocketException e)
{
Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
return (e.ErrorCode);
}
return 0;
}
你的Receive的参数与返回值太让人疑惑了。 --------------------编程问答-------------------- 继续顶! --------------------编程问答-------------------- 帮up --------------------编程问答-------------------- 你看看这。。。。。
public void Send()
{
try{
tcp=new TcpClient ("127.0.0.1",51888);
tcp.Connect("127.0.0.1",51888);
networkstream =tcp.GetStream ();
byte []bt= System .Text .Encoding .Default .GetBytes(Sendtext );
networkstream .Write (bt,0,bt.Length );
networkstream .Flush ();
networkstream .Close ();
}
catch (SocketException e)
{errstring=e.Message ;
return ;
}
}
public void StartListen()
{
Thread startlistenthread = new Thread(new ThreadStart(listenPort));
}
void ListenPort()
{
listen.Start();
while (true)
{tcp =null;
try
{
tcp=listen .AcceptTcpClient();
}
catch (SocketException e)
{
this.errstring =e.Message ;
return ;
}
///////////////////////接收数据
Thread receive=new Thread (new ThreadStart (Receive));
riceive.Start();
///////////////////////////////
}
}
public void CloseListen()
{
throw new System.NotImplementedException();
if(listen!=null)
{listen =null ;}
}
public void Receive()
{
networkstream =tcp.GetStream();
while (true)
{
byte []bt=new byte [1024];
networkstream .Read (bt,0,bt.Length );
recevietext =System .Text .Encoding.Default .GetString (bt);
networkstream .Close ();
}
} --------------------编程问答-------------------- --------------------编程问答-------------------- 调试服务端程序,看看是哪里出错,你可以将程序代码用try... catch...包围,打印错误信息log到文件中看看是什么错误。 --------------------编程问答-------------------- 在顶!
补充:.NET技术 , C#