≡≡JABBY's Blog≡≡

菩提本无树,明镜亦非台,本来无一物,何处惹尘埃

用Visual C#实现P2P应用程序(2)

2.Sender类:

Sender类就一个函数,所以是相当简单的。

代码以及注释如下:
namespace P2PTest 

{

 using System;

 using System.IO;

 using System.Net.Sockets;

 public class Sender

 {

public void Send(string[] aInput)

{

 string stream = "";

 //获得要发送的信息

 for(int i=2; i
 {

stream += aInput[i] + " ";

 }

try

{

 TcpClient tcpc = new TcpClient(aInput[1], 5656);

 //在5656端口新建一个TcpClient对象

 NetworkStream tcpStream = tcpc.GetStream();

 StreamWriter reqStreamW = new StreamWriter(tcpStream);

 reqStreamW.Write(stream);

 reqStreamW.Flush();//发送信息

 tcpStream.Close();

 tcpc.Close();

}

catch(Exception)

{

 Console.WriteLine("connection refused by target computer");

}

}

 }

}


对Send()函数的补充说明:

Send(string[] aInput)函数将一个数组作为参数。数组的第一个元素Send(aInput[0])必须包含"send"这个字,否则Sender对象不会被创建(更多内容在InputHandler类中);第二个元素包含了目标计算机的IP地址;剩下的就是要发送的内容信息了。

在try块中,我们根据远程计算机的IP地址在端口5656(要确保端口号统一)创建了一个TcpClient对象。然后,我们建立一个NetworkStream和一个StremWriter对象来发送我们的信息。在catch块中,我们用它来捕获一般的例外,比如远程计算机拒绝连接请求、网络不通什么的。

3.InputHandler类:

InputHandler类主要用来控制用户输入。

代码以及注释如下:



namespace P2PTest

{

 using System;

 public class InputHandler

 {

public bool appRun = true;//当appRun为false时,程序结束

public InputHandler()

{

 Console.WriteLine("type help for a list of commands.");

 Input();

}

private static Listener li;//一个静态的Listener对象

private string inparam;

private string[] aInput;//数组aInput用于接受用户输入的信息

public void Input()

{

 while(appRun)

 {

inparam = Console.ReadLine();

aInput = inparam.Split(' ');

//将inparam分割的目的是为了获得字符串中的第一个字,从而执行以下不同的命令

switch(aInput[0])

{

 case "send"://如果是"send",则新建一个Sender对象并发送信息

Sender se = new Sender();

se.Send(aInput);

break;

 case "start"://如果是"start",则新的开始监听

try

{

 li.listenerRun = false;

 li.Stop();

}

catch(NullReferenceException)

{

;

}

finally

{

 li = new Listener();

}

break;

 case "stop"://如果是"stop",则停止监听

try

{

 li.listenerRun = false;

 li.Stop();

}

catch(NullReferenceException)

{

 ;

}

break;

 case "exit"://退出程序

try

{

 li.listenerRun = false;

 li.Stop();

}

catch(NullReferenceException)

{

 ;

}

finally

{

 appRun = false;

}

break;

 case "help"://显示帮助信息

 Console.WriteLine("Commands:");

 Console.WriteLine("start: starts the listener");

 Console.WriteLine("stop: stops the listener if started");

 Console.WriteLine("send: send sends a message");

 Console.WriteLine("exit: exits the application");

 Console.WriteLine("help: you already know");

 break;

 default:

Console.WriteLine("Invalid command");

break;

}

 }

}

 }

}

对InputHandler类的补充说明:

该类中有一个静态的Listener对象li,一旦计算机运行此程序并执行"start"操作,该计算机就可以成为网络中的服务器来监听其他计算机的连接请求。而该类的核心部分是一个switch case语句系列,通过不同的操作,我们可以使计算机扮演不同的角色:"send"操作表明该计算机相对目的计算机而言成了客户端;而"start"操作就将计算机自身置为服务器端,这正体现了P2P的既是服务器端又是客户端的"非中心化"的原则;同时程序也提供了一些其他的辅助操作。

posted on 2006-05-10 17:32    阅读(244)  评论(0)    收藏  举报

导航