关闭

Socket学习【2】——持续接收数据

675人阅读 评论(0) 收藏 举报
分类:

持续接收数据

服务器端

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 ();
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:879880次
    • 积分:13791
    • 等级:
    • 排名:第950名
    • 原创:436篇
    • 转载:480篇
    • 译文:1篇
    • 评论:87条
    最新评论