二 .开发原理: 服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。 客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序。要学Internet上的TCP/IP网络编程,必须理解Socket接口。 Socket接口设计者最先是将接口放在Unix操作系统里面的。如果了解Unix系统的输入和输出的话,就很容易了解Socket了。网络的Socket数据传输是一种特殊的I/O,Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket(),该函数返回一个整型的Socket描述符,随后的连接建立、数据传输等操作都是通过该Socket实现的。
三.简单的socket 同步代码,目前代码没有上服务器测试,不知道同步和异步的效果怎么样!
需求
1.客户端是公司内部的机器200台计算机。 2.可以同时连接,长连接。 3.服务器接受到客户端发来的信息,发送 socket数据 发送给总公司socket服务器 ,总公司返回数据。
socket 同步简单代码
代码 public class Server { static void Main(string[] args) { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); //创建 socket Tcp Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); while (true) { Socket connection = listener.Accept(); SocketProxy sp = new SocketProxy(connection); Thread thread = new Thread(new ThreadStart(sp.TcpSendData)); thread.Name = connection.RemoteEndPoint.ToString(); thread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } public class SocketProxy { private Socket _socket; public SocketProxy(Socket connection) { this._socket = connection; } public void TcpSendData() { byte[] bytes; string data = string.Empty; while (true) { bytes = new byte[1024]; // Receive client data int bytesRec = this._socket.Receive(bytes); // convert bytes to string data = Encoding.ASCII.GetString(bytes, 0, bytesRec); Console.WriteLine(data); } } }
异步代码
internal class SocketServer { static void Main(string[] args) { SocketTcpListener listener = new SocketTcpListener(); listener.StartListening(); } }
internal class SocketTcpListener { public static ManualResetEvent allDone = new ManualResetEvent(false); //开始监听 public void StartListening() { //Data buffer for incoming data. byte[] bytes = new Byte[1024]; //Establish the local endpoint for the socket. //The DNS name of the computer //running the listener is "host.contoso.com". //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 9050); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(10); while (true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine("Waiting for a connection"); StateObject state = new StateObject(); listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } //异步接受 private static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; Array.Clear(state.buffer, 0, state.buffer.Length); // 清空缓存,避免脏读 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } //异步读取 public static void ReadCallback(IAsyncResult ar) { String content = String.Empty; String resultdata = string.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. // state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = Encoding.ASCII.GetString(state.buffer, 0, bytesRead); Array.Clear(state.buffer, 0, state.buffer.Length); // 清空缓存,避免脏读 Console.WriteLine(content); if (content.Length > -1) { // All the data has been read from the // client. Display it _disibledevent=>//Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); // Echo the data back to the client. //SocketTcpClient.CreateSocketObjest(); // get caac data // 0 如果是第一次,需要创建socket对象,发送登陆信息,匹配出用户名(
///
/// command
///
/// comand
private static void ClientSendDataServer(Socket client, String command) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(command); // Begin sending the data to the remote device. client.Send(byteData); } } ///
///
///
public void Add(string key, Socket sk) { _sockets.Add(key, sk); } ///
public void Remove(string key) { _sockets.Remove(key); } } // socket state
internal class StateObject { // socket name public string SocketName { get; set; } // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public string ResultData { get; set; } }
感谢您的阅读 欢迎大家讨论!
最新评论