关于UdpClient连接订立传送协议并且发送数据,希望有高手来帮帮忙

tyg111 2010-07-05 05:31:49
下面是代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;


// C#网络编程 - Part.4

// 此段代码演示由客户端发送文件到服务端
// 与此对应的代码为ServerConsole项目中的Server1.cs

namespace ClientConsole {

class Program {
static void Main(string[] args) {

ServerClient client = new ServerClient();
string input;
string path = Environment.CurrentDirectory + "/";

do {
Console.WriteLine("Send File: S1 - Client01.jpg, S2 - Client02.jpg, S3 - Client03.jpg");
Console.WriteLine("Receive File: R1 - Server01.jpg, R1 - Server02.jpg, R3- Server03.jpg");
Console.WriteLine("Press 'Q' to exit. \n");
Console.Write("Enter your choice: ");
input =Console .ReadLine ();
switch(input.ToUpper()){
case "S1":
client.BeginSendFile(path + "Client01.jpg");
break;
case "S2":
client.BeginSendFile(path + "Client02.jpg");
break;
case "S3":
client.BeginSendFile(path + "Client03.jpg");
break;
case "R1":
client.BeginReceiveFile("Server01.jpg");
break;
case "R2":
client.BeginReceiveFile("Server02.jpg");
break;
case "R3":
client.BeginReceiveFile("Server03.jpg");
break;
}
} while (input.ToUpper() != "Q");

client.Dispose();
}
}


public class ServerClient :IDisposable {
private const int BufferSize = 8192;
private byte[] buffer;
private UdpClient client;
private NetworkStream streamToServer;

public ServerClient() {
try {
client = new UdpClient ();
client.Connect("192.168.1.7", 8005); // 与服务器连接
} catch (Exception ex) {
Console.WriteLine(ex.Message);
return;
}
buffer = new byte[BufferSize];

// 打印连接到的服务端信息
Console.WriteLine("Server Connected!{0} --> {1}\n",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint);


//streamToServer .Write (buffer ,0,BufferSize );
}

// 发送消息到服务端
public void SendMessage(string msg) {

byte[] temp = Encoding.Unicode.GetBytes(msg); // 获得缓存
try {
lock (streamToServer ){
streamToServer.Write(temp, 0, temp.Length); // 发往服务器
}
Console.WriteLine("Sent: {0}", msg);
} catch (Exception ex) {
Console.WriteLine("\n do something wrong!!! \n");
Console.WriteLine(ex.Message);
return;
}
}

// 发送文件 - 异步方法
public void BeginSendFile(string filePath) {
ParameterizedThreadStart start =
new ParameterizedThreadStart(SendFile);
start.BeginInvoke(filePath, null, null);
}

private void SendFile(object obj) {
string filePath = obj as string;
SendFile(filePath);
}

// 发送文件 -- 同步方法
public void SendFile(string filePath) {

IPAddress ip = IPAddress.Parse("192.168.1.7");


// 获取本地侦听的端口号
IPEndPoint endPoint = new IPEndPoint(ip,8005);
UdpClient client = new UdpClient();
//client.Client.Listen(4);
int listeningPort = endPoint.Port;

// 获取发送的协议字符串
string fileName = Path.GetFileName(filePath);
FileProtocol protocol =
new FileProtocol(FileRequestMode.Send, listeningPort, fileName);
string pro = protocol.ToString();

SendMessage(pro); // 发送协议到服务端

// 中断,等待远程连接

client .Connect (endPoint );
Console.WriteLine("Start sending file...");
// 把流写入数组里面
// streamToServer .Write (buffer ,0,BufferSize );

// 创建文件流
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] fileBuffer = new byte[1024]; // 每次传1KB
int bytesRead;
int totalBytes = 0;

// 创建获取文件发送状态的类
SendStatus status = new SendStatus(filePath);

// 将文件流转写入网络流
try {
do {
Thread.Sleep(10); // 为了更好的视觉效果,暂停10毫秒:-)
bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length);
//streamToServer .Write(fileBuffer, 0, bytesRead);
totalBytes += bytesRead; // 发送了的字节数
status.PrintStatus(totalBytes); // 打印发送状态
} while (bytesRead > 0);
Console.WriteLine("Total {0} bytes sent, Done!", totalBytes);
} catch {
Console.WriteLine("Server has lost...");
}

// streamToServer.Dispose();
fs.Dispose();
client.Close();
client .Close ();
}

// 接收文件 -- 异步方法
public void BeginReceiveFile(string fileName) {
ParameterizedThreadStart start =
new ParameterizedThreadStart(ReceiveFile);
start.BeginInvoke(fileName, null, null);
}

public void ReceiveFile(object obj) {
string fileName = obj as string;
ReceiveFile(fileName);
}


// 接收文件 -- 同步方法
public void ReceiveFile(string fileName) {

IPAddress ip = IPAddress.Parse("192.168.1.7");
UdpClient client=new UdpClient ();
//client .Client .Listen (4);

// 获取本地侦听的端口号
IPEndPoint endPoint = new IPEndPoint (ip,8005);
int listeningPort = endPoint.Port;

// 获取发送的协议字符串
FileProtocol protocol =
new FileProtocol(FileRequestMode.Receive, listeningPort, fileName);
string pro = protocol.ToString();

SendMessage(pro); // 发送协议到服务端

// 中断,等待远程连接
client .Connect (endPoint );
Console.WriteLine("Start sending file...");
//streamToServer.Write (buffer ,0,BufferSize );
// 获取文件保存的路劲
string filePath =
Environment.CurrentDirectory + "/" + generateFileName(fileName);

// 创建文件流
FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
byte[] fileBuffer = new byte[1024]; // 每次传1KB
int bytesRead;
int totalBytes = 0;

// 从缓存buffer中读入到文件流中
do {
bytesRead = streamToServer.Read(buffer, 0, BufferSize);
fs.Write(fileBuffer, 0, bytesRead);
totalBytes += bytesRead;
Console.WriteLine("Receiving {0} bytes ...", totalBytes);
} while (bytesRead > 0);

Console.WriteLine("Total {0} bytes received, Done!", totalBytes);

fs.Dispose();
//streamToServer.Dispose();
client .Close ();
}


// 随机获取一个图片名称
private string generateFileName(string fileName) {
DateTime now = DateTime.Now;
return String.Format(
"{0}_{1}_{2}_{3}", now.Minute, now.Second, now.Millisecond, fileName
);
}

public void Dispose() {
if (streamToServer != null)
streamToServer.Dispose();
if (client != null)
client.Close();
}

}

}
上面是客户端的代码。这个是我自己根据别人TCPClient连接写的,到最后自己都不知道是什么意思了,希望高手来帮帮忙,这个里面就是连接不对,其他的问题都基本上解决了。
下面的是服务端的代码:
...全文
310 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
eryx_wu 2011-05-07
  • 打赏
  • 举报
回复
楼主,能把解决的代码贴出来学习下吗?
tyg111 2010-07-14
  • 打赏
  • 举报
回复
目前还有点小问题,等写好了,我再传上去
tyg111 2010-07-14
  • 打赏
  • 举报
回复
我该用socket,udp了
  • 打赏
  • 举报
回复
分倒是不要,不过想知道问题出在哪里,楼主是怎么解决的,也好学习一下
tyg111 2010-07-14
  • 打赏
  • 举报
回复
问题解决了,谁要分?
tyg111 2010-07-07
  • 打赏
  • 举报
回复
来个高手啊
平生我自如 2010-07-06
  • 打赏
  • 举报
回复
帮顶一下…………
tyg111 2010-07-05
  • 打赏
  • 举报
回复
我也不知道错哪了,他就是能连接上服务器,但是不能传输数据,我想用数组来传送数据,但是不知道怎么写
xk1126 2010-07-05
  • 打赏
  • 举报
回复
lz你贴这么多代码
让人怎么看啊!
你把错误的地方给贴出来啊!~
tyg111 2010-07-05
  • 打赏
  • 举报
回复
希望高手来帮帮忙
tyg111 2010-07-05
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.Text;
using System.IO ;
using System.Net ;
using System.Net .Sockets ;
using System.Threading;

namespace ServerConsole
{
class Server1
{
static void Main(string[] args)
{
Console.WriteLine ("server is connecting...");
UdpClient client=new UdpClient (8005);
IPEndPoint ipep=new IPEndPoint (IPAddress .Any ,8005);
// client .Client .Listen (4);
while (true )
{
client.Connect(Dns.GetHostName().ToString(), 8005);
RemoteClient war=new RemoteClient (client );
war.BeginRead ();
}
}

public class RemoteClient
{
private UdpClient Rclient;
private byte[] data;
private ProtocolHandler handler;
private NetworkStream streamToClient;

public RemoteClient (UdpClient client)
{
IPEndPoint remote = new IPEndPoint(IPAddress .Any , 8005); ;

Console.WriteLine("\nClient Connected!{0} <-- {1}",
client.Client.LocalEndPoint , client.Client.RemoteEndPoint);

data =client.Receive (ref remote );
data=new Byte [8192] ;
handler=new ProtocolHandler();
}

public void BeginRead()
{
AsyncCallback callBack=new AsyncCallback (OnReadComplete);
streamToClient .BeginRead (data,0,data.Length ,OnReadComplete,null);
}

private void OnReadComplete(IAsyncResult ar)
{
int recv=0;
IPEndPoint remote=new IPEndPoint (IPAddress .Any ,8005);
Rclient =new UdpClient ();
try{
lock (Rclient ){
data=Rclient .EndReceive (ar,ref remote );
Console .WriteLine ("Reading data, {0} bytes ...", data);
}
if(recv ==0) throw new Exception ("读取到零字节");

string msg=Encoding .ASCII .GetString (data,0,recv );
Array .Clear(data,0,data.Length );
string[] protocolArray=handler.GetProtocol(msg);
foreach (string pro in protocolArray )
{
ParameterizedThreadStart start=new ParameterizedThreadStart (handleProtocol);
start .BeginInvoke (pro,null,null);
}
lock (Rclient )
{
AsyncCallback callback=new AsyncCallback (OnReadComplete);
streamToClient .BeginRead (data,0,data .Length ,OnReadComplete,null);
}
}catch (Exception ex)
{
if(Rclient != null)
Rclient .Close ();

Console .WriteLine (ex.Message );
}

}

//处理protocol
private void handleProtocol(object obj) {
string pro = obj as string;
ProtocolHelper helper = new ProtocolHelper(pro);
FileProtocol protocol = helper.GetProtocol();

if (protocol.Mode == FileRequestMode.Send) {
// 客户端发送文件,对服务端来说则是接收文件
receiveFile(protocol);
} else if (protocol.Mode == FileRequestMode.Receive) {
// 客户端接收文件,对服务端来说则是发送文件
SendFile(protocol);
}
}
//发送文件
private void SendFile(FileProtocol protocol)
{
UdpClient client;
NetworkStream streamToClient=getStreamToClient(protocol ,out client );
string filePath=Environment.CurrentDirectory +"/"+protocol .FileName ;
FileStream fs=new FileStream (filePath ,FileMode .Open ,FileAccess .Read );
byte[] fileBuffer=new byte[1024];

try{
int bytesRead;
int totalBytes = 0;

// 创建获取文件发送状态的类
SendStatus status = new SendStatus(filePath);

// 将文件流转写入网络流
try
{
do
{
Thread.Sleep(10); // 为了更好的视觉效果,暂停10毫秒:-)
bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length);
streamToClient.Write(fileBuffer, 0, bytesRead);
totalBytes += bytesRead; // 发送了的字节数
status.PrintStatus(totalBytes); // 打印发送状态
} while (bytesRead > 0);
Console.WriteLine("Total {0} bytes sent, Done!", totalBytes);
}
catch
{
Console.WriteLine("Server has lost...");
}

streamToClient.Dispose();
fs.Dispose();
client.Close();
}catch (Exception ex)
{
Console .WriteLine (ex.Message );
}

}
// 接收文件
private void receiveFile(FileProtocol protocol)
{
UdpClient localClient;
NetworkStream streamToClient = getStreamToClient(protocol, out localClient);
if (streamToClient == null) return;

// 随机生成一个在当前目录下的文件名称
string path =
Environment.CurrentDirectory + "/" + generateFileName(protocol.FileName);

byte[] fileBuffer = new byte[1024]; // 每次收1KB
FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);

// 从缓存buffer中读入到文件流中
int bytesRead;
int totalBytes = 0;
do
{
bytesRead = streamToClient.Read(data, 0, data.Length );
fs.Write(data, 0, bytesRead);
totalBytes += bytesRead;
Console.WriteLine("Receiving {0} bytes ...", totalBytes);
} while (bytesRead > 0);

Console.WriteLine("Total {0} bytes received, Done!", totalBytes);

streamToClient.Dispose();
fs.Dispose();
localClient.Close();
}


// 获取连接到远程的流 -- 公共方法
private NetworkStream getStreamToClient(FileProtocol protocol, out UdpClient localClient) {
// 获取远程客户端的位置
IPEndPoint endpoint = Rclient .Client .RemoteEndPoint as IPEndPoint ;
IPAddress ip = endpoint.Address;

// 使用新端口号,获得远程用于接收文件的端口
endpoint = new IPEndPoint(ip, protocol.Port);

// 连接到远程客户端
try
{
localClient = new UdpClient();
localClient.Connect(endpoint);
}
catch
{
Console.WriteLine("无法连接到客户端 --> {0}", endpoint);
localClient = null;
return null;
}

// 获取发送文件的流
data=Encoding.ASCII.GetBytes("123");

streamToClient .Write (data,0,data .Length );

return streamToClient;
}

// 随机获取一个图片名称
private string generateFileName(string fileName)
{
DateTime now = DateTime.Now;
return String.Format(
"{0}_{1}_{2}_{3}", now.Minute, now.Second, now.Millisecond, fileName
);
}


}

}
}


小弟分不多,聊表心意

110,533

社区成员

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

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

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