Socket學習【2】——持續接收資料
阿新 • • 發佈:2019-01-22
持續接收資料
伺服器端
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace SocketServer { class Program { static Socket clientSocket = null; static void Main(string[] args) { List<byte[]> byteCache = new List<byte[]>(); byte[] buff = new byte[1024]; //建立Socket Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipaddress = IPAddress.Parse("192.168.0.99"); IPEndPoint endpoint = new IPEndPoint(ipaddress, 50000); tcpServer.Bind(endpoint); tcpServer.Listen(100); Console.WriteLine("伺服器啟動完成"); //收到客戶端Socket clientSocket = tcpServer.Accept(); Console.WriteLine("接收到客戶端的連結請求"); //向客戶端傳送訊息 string message = "Hello Client"; var data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); Console.WriteLine("伺服器向客戶端傳送了一條訊息" + message); int length = 0; while( true ) { if( clientSocket == null ) { continue; } ZeroMemory(buff, 1024); length = Program.ReceiveData( buff, 1024 ); if( length != -1 && length != 0 ) { byteCache.Add(buff); } else { Console.WriteLine("收取資料錯誤"); } } } static int ReceiveData( byte[] buff, int size ) { try { int length = clientSocket.Receive(buff); string message2 = Encoding.UTF8.GetString(buff, 0, length); Console.WriteLine("收到伺服器傳送訊息" + message2); return length; } catch (SocketException ex) { return -1; } } static void ZeroMemory( byte[] buff, int buffSize ) { for (int i = 0; i < buffSize; i++) { buff[i] = (byte)0; } } } }
客戶端:本客戶端程式碼還是藉助上篇的封裝類SocketClient
using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; public class SocketTest : MonoBehaviour { private string m_host = "192.168.0.99"; private int m_port = 50000; private Socket m_client = null; private byte[] m_BufferTemp = new byte[1024]; private uint receLength = 0u; void Start() { string empty = string.Empty; m_client = SocketClient.Connect( this.m_host, this.m_port, ref empty ); if( m_client != null ) { string sendMessage = "Client send message help" + Time.realtimeSinceStartup; m_client.Send( System.Text.Encoding.ASCII.GetBytes(sendMessage) ); } if( m_client != null ) { receLength = SocketClient.Recv( this.m_client, this.m_BufferTemp, 1024u, 0u ); if( receLength != 0u && receLength != 4294967295u ) { string str = System.Text.Encoding.UTF8.GetString( this.m_BufferTemp ); Debug.Log( "get from server " + str + receLength + " bytes" ); receLength = 0u; } } InvokeRepeating ("sendData", 1f, 1f); } void sendData() { string sendMessage = "Client send message help" + Time.realtimeSinceStartup; m_client.Send( System.Text.Encoding.ASCII.GetBytes(sendMessage) ); } void OnDestroy() { CancelInvoke ("sendData"); this.m_client.Shutdown (SocketShutdown.Both); this.m_client.Close (); } }