学习socket必看发送接收经典案例.doc
文本预览下载声明
Socket经典的接受-----发送文件案例
说明
本文基于VS2005开发平台,VC++语言,控制台console程序。经本机测试,能够通过。
socket说明:其实就是微软的API。里面有很多函数供大家使用。其实大家很多时候都比较模糊,API是什么东东。我在这里,向大家简单说下我的理解,很简单就是程序员做了很多类,类里面有很多方法,俗称组件。放在服务器上,然后开发出一个接口,供大家使用。大家可以基于这个接口,开发很多程序。就这么简单,呵呵,可能我表述的不是很准确,还请大家多多包涵。不用多说,直接上案例。
socket发送的目的地址方式为:IP+port方式。如1:22
本案例有两个文件,一个是客户端程序(client.cs);一个是服务器端程序(server.cs)。
客户端程序代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpclient
{
/// summary
/// Class1 的摘要说明。
/// /summary
class client
{
/// summary
/// 应用程序的主入口点。
/// /summary
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
byte[] data = new byte[1024];
Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write( please input the server ip: );
string ipadd = Console.ReadLine();
Console.WriteLine();
Console.Write( please input the server port: );
int port = Convert.ToInt32(Console.ReadLine());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port); // 服务器的IP和端口
try
{
// 因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ie);
}
catch (SocketException e)
{
Console.WriteLine( unable to connect to server );
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
while (true)
{
string input = Console.ReadLine();
if (input == exit )
break;
newclient.Send(Encoding.ASCII.GetBytes(input));
data = new
显示全部