Socketサーバ学習

6521 ワード

目標:簡単な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();

});
三、ユニティクライアントプログラム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+"
"; } 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)+"
"; } 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); } }