Socket服务器学习

目标:实现一个简单的Socket聊天服务器

服务端环境:NodeJS

客户端:Mac终端+NodeJS,Unity

 

一、服务器程序

var net = require('net');

var timeout = 60000;

var mess="";

var clientlist=[];

//超时

var listenPort = 1234;

//监听端口

function sendall(socket,message){

        for(var i=0;i<clientlist.length;i++){

                if(clientlist[i].writable){

                        if(clientlist[i]!=socket)

                                clientlist[i].write(socket.remotePort+':'+message);

                }else{

                        clientlist[i].destroy();

                }

        }

}



var server = net.createServer(function(socket) {

        clientlist.push(socket);

// 我们获得一个连接 - 该连接自动关联一个socket对象

        mess=socket.remoteAddress + ':' + socket.remotePort;

        console.log('start连接>> ' + mess);

//      socket.setEncoding('binary');

        //超时事件

        socket.setTimeout(timeout, function() {

                console.log('连接超时');

                socket.end();

        });

        //接收到数据

        socket.on('data', function(data) {

                sendall(socket,data);

                console.log(data.toString('utf8'));

        });

        //数据错误事件

        socket.on('error', function(exception) {

                console.log('socket error:' + exception);

                socket.end();

        });

        //客户端关闭事件

        socket.on('end', function(data) {

                console.log('  end连接>> ' + mess);

        });

        socket.on('close', function(data) {

                console.log('close连接>> ' + mess);

                console.log('**********************************');

        });

}).listen(listenPort);

//服务器监听事件

server.on('listening', function() {

        console.log("server listening:" + server.address().port);

});

//服务器错误事件

server.on("error", function(exception) {

        console.log("server error:" + exception);

});

二、Mac终端 客户端程序

var net = require('net');

var host = process.argv[2];

var port =Number(process.argv[3]);



var socket = net.connect(port,host);

var inbuffer;

socket.on('connect',function(){

process.stdin.resume();

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {  

      socket.write(chunk);  

});  





});

//socket.setEncoding('utf8');

socket.on('data',function(data){

    console.log(data.toString('utf8'));

});

socket.on('end',function(){

    process.stdin.pause();

});

三、Unity客户端程序C#脚本

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.Collections.Generic;

using System.IO;

using System.Runtime.InteropServices;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary; 



public class TestSocket : MonoBehaviour {



    string say="";



    string mes="";



    string rec="";



    Socket clientSocket;



    public void ConncetServer(){

        IPAddress ip = IPAddress.Parse ("127.0.0.1");

        IPEndPoint endpoint = new IPEndPoint (ip, 1234);

        if (clientSocket!=null&&clientSocket.Connected) {

                        Debug.Log ("connected already");    

                        mes="connected already";

                } else {



            if(clientSocket!=null){

                IAsyncResult result=clientSocket.BeginConnect(endpoint,new AsyncCallback(connectCallback),clientSocket);

                

                bool success=result.AsyncWaitHandle.WaitOne(5000,true);

                

                if(!success){

                    clientSocket.Close ();

                    Debug.Log("connection timed out");

                    mes="connection timed out";

                }else{

                    Thread thread=new Thread(new ThreadStart(receiveSocket));

                    thread.IsBackground=true;

                    thread.Start();

                }

            }



        }

    }



    void Send(){



        if (clientSocket.Connected) {

            try{

                byte[] sendmsg = Encoding.UTF8.GetBytes (say);

                

                clientSocket.Send (sendmsg);



                rec+="me:  "+say+"\n";

            }    catch (Exception e){

                Debug.Log("exception happend during sending message :  "+e);

            }        



                } else {

            Debug.Log("need connection");

            mes="need connection";

        }



    }



    void CloseSocket(){

        clientSocket.Close ();

        mes = "closed.";

    }



    void connectCallback(IAsyncResult connect){

        Debug.Log ("connection started");

    }



    void receiveSocket(){

        while (clientSocket.Connected) {

            try{

                byte[] bytes=new byte[4096];

                clientSocket.Receive(bytes);

                rec+=Encoding.UTF8.GetString(bytes)+"\n";





                                     }    catch (Exception e){

                    mes="exception: "+e;

                    clientSocket.Close();

                    Debug.Log("exception;  "+e);

                }

        }

    }



    // Use this for initialization

    void Start () {

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

    }

    

    // Update is called once per frame

    void Update () {

    

    }



    void OnGUI(){

        say = GUI.TextField (new Rect(0.0f,Screen.height*0.5f+5.0f,Screen.width-105.0f,50.0f),say);

        if(GUI.Button(new Rect(0.0f,Screen.height * 0.5f+60.0f,100.0f,50.0f),"connect"))

            ConncetServer();

        if (GUI.Button (new Rect (Screen.width - 100.0f, Screen.height * 0.5f + 5.0f, 100.0f, 50.0f), "send")) {

            Send ();

            say="";

        }

        if(GUI.Button(new Rect(105.0f,Screen.height * 0.5f+60.0f,100.0f,50.0f),"close"))

            CloseSocket();

        GUI.Label (new Rect (220.0f, Screen.height * 0.5f + 170.0f, 100.0f, 25.0f), mes);

        GUI.TextArea (new Rect(0.0f,0.0f,Screen.width,Screen.height*0.5f),rec);

    }

}

 

 

你可能感兴趣的:(socket)