Socket伺服器學習(一)

來源:互聯網
上載者:User

標籤:des   style   blog   color   width   資料   

目標:實現一個簡單的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);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.