您的位置:首页 > 其它

面向连接的套接字

2007-07-05 14:27 162 查看
在服务器能够向客户机传输数据之前,必须做以下四件事:

1、创建一个套接字

2、将所创建的套接字与本地IPEndPoint绑定

3、设置套接字为收听模式

4、在套接字上接收接入的连接

创建一个简单的TCP服务器:


using System;


using System.Collections.Generic;


using System.Text;


using System.Net;


using System.Net.Sockets;




namespace SimpleTcpSrvr1




...{


class Program




...{


static void Main(string[] args)




...{


int recv;


byte[] data = new byte[1024];


IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);


Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


newsock.Bind(ipep);


newsock.Listen(10);


Console.WriteLine("Waiting for a client...");


Socket client = newsock.Accept();


IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;


Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);


string welcome = "Welcome to my test sever";


data = Encoding.ASCII.GetBytes(welcome);


client.Send(data, data.Length, SocketFlags.None);


while (true)




...{


data = new byte[1024];


recv =client.Receive(data);


if (recv == 0)


break;


Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));


client.Send(data, recv, SocketFlags.None);


}


Console.WriteLine("Disconnected from {0}", clientep.Address);


client.Close();


newsock.Close();


Console.Read();


}


}


}



这个程序中没有任何修饰或技巧。首先,定义一个空字节数组作为数据缓冲器,用于缓存流入和流出的消息。不论传输什么类型的数据Socket Receive()和Send()只能使用字节数组,所有通过这个Socket传输的数据必须转换为字节数组。

接下来为本地服务器定义IPEndPoint对象:IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

接下来调用Socket()构造函数创建TCP套接字,然后使用Bind()和Listen()将该套接字与新IPEndPoint对象进行绑定,并收听接入连接。

最后,使用Accept()方法接收来自客户机的接入连接尝试,Accept()返回一个Socket对象在与客户机的所有通信中必须使用这个新的Socket对象。

用命令 telnet 127.0.0.1 9050 测试服务器。

简单的客户机程序


using System;


using System.Collections.Generic;


using System.Text;


using System.Net;


using System.Net.Sockets;




namespace SimpleTcpClient




...{


class Program




...{


static void Main(string[] args)




...{


byte[] data = new byte[1024];


string input, stringData;


IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);


Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


try




...{


server.Connect(ipep);


}


catch(SocketException e)




...{


Console.WriteLine("Unable to connect to server");


Console.WriteLine(e.ToString());


Console.ReadLine();


return;


}


int recv = server.Receive(data);


stringData = Encoding.ASCII.GetString(data,0,recv);


Console.WriteLine(stringData);


while (true)




...{


input = Console.ReadLine();


if (input == "exit")


break;


server.Send(Encoding.ASCII.GetBytes(input));


data = new byte[1024];


recv = server.Receive(data);


stringData = Encoding.ASCII.GetString(data, 0, recv);


Console.WriteLine(stringData);


}


Console.WriteLine("Disconnecting from server...");


server.Shutdown(SocketShutdown.Both);


server.Close();


}


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: