C#传送文件可以不用UDP用WebClientConsole.Write("\nPlease enter the URL to post data to : "); String uriString = Console.ReadLine();// Create a new WebClient instance. WebClient myWebClient = new WebClient();Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URL"); string fileName = Console.ReadLine();Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString); // Upload the file to the URL using the HTTP 1.0 POST. byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);// Decode and display the response. Console.WriteLine("\nResponse Received.The contents of the file uploaded are: \n{0}",Encoding.ASCII.GetString(responseArray));
设置 TcpClient 以连接到 TCP 端口 13 上的时间服务器。[C#]using System;using System.Net.Sockets;using System.Text; public class TcpTimeClient {private const int portNum = 13;private const string hostName = "host.contoso.com"; public static int Main(String[] args) {try {TcpClient client = new TcpClient(hostName, portNum); NetworkStream ns = client.GetStream(); byte[] bytes = new byte[1024];int bytesRead = ns.Read(bytes, 0, bytes.Length); Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead)); client.Close(); } catch (Exception e) {Console.WriteLine(e.ToString());} return 0;}}
使用 TcpListener 创建网络时间服务器以监视 TCP 端口 13。当接受传入的连接请求时,时间服务器用来自宿主服务器的当前日期和时间进行响应。[C#]using System;using System.Net.Sockets;using System.Text; public class TcpTimeServer { private const int portNum = 13; public static int Main(String[] args) {bool done = false; TcpListener listener = new TcpListener(portNum); listener.Start(); while (!done) {Console.Write("Waiting for connection...");TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Connection accepted.");NetworkStream ns = client.GetStream(); byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString()); try {ns.Write(byteTime, 0, byteTime.Length);ns.Close();client.Close();} catch (Exception e) {Console.WriteLine(e.ToString());}} listener.Stop(); return 0;} }
下面的示例使用 UdpClient 侦听端口 11000 上的多路广播地址组 224.168.100.2 的 UDP 数据文报广播。它接收消息字符串并将消息写入控制台。[C#] using System; using System.Net; using System.Net.Sockets; using System.Text;public class UDPMulticastListener { private static readonly IPAddress GroupAddress = IPAddress.Parse("224.168.100.2"); private const int GroupPort = 11000;
} public static int Main(String[] args) { Send(args[0]); return 0; } }
using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; namespace Socket_Server { /// <summary> /// cls_SocketServer 的摘要说明。 /// 套接字服务器端类 /// </summary> public delegate void SocketAccepted(Socket socket); public delegate void SocketInfoArrival(Socket socket, string infomation); public class cls_SocketServer { public Socket m_socket; public Socket u_socket; private Thread m_Thread; private ManualResetEvent allDone = new ManualResetEvent(false); private byte[] received = new byte[1024]; private uint connectNum = 0;
public event SocketAccepted socketaccepted; public event SocketInfoArrival socketinfoarrival;
String uriString = Console.ReadLine();// Create a new WebClient instance.
WebClient myWebClient = new WebClient();Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URL");
string fileName = Console.ReadLine();Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URL using the HTTP 1.0 POST.
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);// Decode and display the response.
Console.WriteLine("\nResponse Received.The contents of the file uploaded are: \n{0}",Encoding.ASCII.GetString(responseArray));
public class TcpTimeClient {private const int portNum = 13;private const string hostName = "host.contoso.com";
public static int Main(String[] args) {try {TcpClient client = new TcpClient(hostName, portNum);
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];int bytesRead = ns.Read(bytes, 0, bytes.Length);
Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead));
client.Close();
} catch (Exception e) {Console.WriteLine(e.ToString());}
return 0;}}
public class TcpTimeServer {
private const int portNum = 13;
public static int Main(String[] args) {bool done = false;
TcpListener listener = new TcpListener(portNum);
listener.Start();
while (!done) {Console.Write("Waiting for connection...");TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");NetworkStream ns = client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try {ns.Write(byteTime, 0, byteTime.Length);ns.Close();client.Close();} catch (Exception e) {Console.WriteLine(e.ToString());}}
listener.Stop();
return 0;}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;public class UDPMulticastListener { private static readonly IPAddress GroupAddress =
IPAddress.Parse("224.168.100.2");
private const int GroupPort = 11000;
private static void StartListener() {
bool done = false;
UdpClient listener = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort); try {
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
while (!done) {
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive( ref groupEP); Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes,0,bytes.Length));
} listener.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
} public static int Main(String[] args) {
StartListener(); return 0;
}
}
下面的示例使用 UdpClient 将 UDP 数据文报发送到端口 11000 上的多路广播地址组 224.268.100.2。它发送命令行上指定的消息字符串。[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;public class UDPMulticastSender { private static IPAddress GroupAddress =
IPAddress.Parse("224.168.100.2");
private static int GroupPort = 11000;
private static void Send( String message) {
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort); try {
Console.WriteLine("Sending datagram : {0}", message);
byte[] bytes = Encoding.ASCII.GetBytes(message); sender.Send(bytes, bytes.Length, groupEP);
sender.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
} public static int Main(String[] args) {
Send(args[0]); return 0;
}
}
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace Socket_Server
{
/// <summary>
/// cls_SocketServer 的摘要说明。
/// 套接字服务器端类
/// </summary>
public delegate void SocketAccepted(Socket socket);
public delegate void SocketInfoArrival(Socket socket, string infomation);
public class cls_SocketServer
{
public Socket m_socket;
public Socket u_socket; private Thread m_Thread;
private ManualResetEvent allDone = new ManualResetEvent(false);
private byte[] received = new byte[1024];
private uint connectNum = 0;
public event SocketAccepted socketaccepted;
public event SocketInfoArrival socketinfoarrival;
public cls_SocketServer(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
//
// TODO: 在此处添加构造函数逻辑
//参数表:addressFamily:解析地址的寻址方案, socketType:套接字类型,protocolType:协议类型
//
m_socket = new Socket(addressFamily, socketType, protocolType);
} public void socketListen(int port)
{
//套接字进行监听
//参数表:port:进行监听的端口号
try
{
IPHostEntry m_local = Dns.Resolve(Dns.GetHostName());
IPEndPoint ipendPoint = new IPEndPoint(IPAddress.Parse(m_local.AddressList[0].ToString()), port);
m_socket.Bind(ipendPoint);
m_socket.Listen(20); m_Thread = new Thread(new ThreadStart(MainThread));
m_Thread.Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
} private void AsyncAccept(IAsyncResult ar)
{
//异步回调接受连接请求
try
{
allDone.Set();
Socket a_socket = (Socket)ar.AsyncState;
Socket handle = a_socket.EndAccept(ar);
socketaccepted(handle);
//进行异步接收数据
handle.BeginReceive(received, 0, received.Length, SocketFlags.None, new AsyncCallback(AsyncReceive), handle);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
} private void AsyncReceive(IAsyncResult ar)
{
//异步回调接收数据
try
{
Socket r_socket = (Socket) ar.AsyncState;
int read = r_socket.EndReceive(ar);
if(read > 0)
{
string result = Encoding.Default.GetString(received);
Console.WriteLine(result);
socketinfoarrival(r_socket, result);
r_socket.BeginReceive(received, 0, received.Length, SocketFlags.None, new AsyncCallback(AsyncReceive), r_socket);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
} private void MainThread()
{
try
{
while(true)
{
allDone.Reset();
Console.WriteLine("Waiting For Connection. . .");
m_socket.BeginAccept(new AsyncCallback(AsyncAccept), m_socket);
allDone.WaitOne(3000, true);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
} public void CloseSocket()
{
m_Thread.Abort();
m_socket.Close();
}
}
}
http://dev.csdn.net/develop/article/22/22197.shtm