標籤: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); }}