Socket server Learning (1)

Source: Internet
Author: User
Tags sendmsg socket error

Objective: To implement a simple socket Chat Server

Server Environment: nodejs

Client: Mac terminal + nodejs, unity

 

I. server programs

VaR net = require ('net'); var timeout = 60000; var mess = ""; var clientlist = []; // timeout var listenport = 1234; // listening port 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); // we get a connection-the connection is automatically associated with a socket object mess = socket. remoteaddress + ':' + socket. remoteport; console. log ('start connection> '+ mess); // socket. setencoding ('binary '); // timeout event socket. setTimeout (timeout, function () {console. log ('Connection timeout'); socket. end () ;}); // receives the data socket. on ('data', function (data) {sendall (socket, data); console. log (data. tostring ('utf8');}); // data error event socket. on ('error', function (exception) {console. log ('socket error: '+ exception); socket. end () ;}); // The client closes the event socket. on ('end', function (data) {console. log ('end connection >>' + mess) ;}); socket. on ('close', function (data) {console. log ('close connection> '+ mess); console. log ('**********************************'); });}). listen (listenport); // The server listens to the Event Server. on ('listenering', function () {console. log ("server listening:" + server. address (). port) ;}); // Server Error Event Server. on ("error", function (exception) {console. log ("server error:" + exception );});

 

Ii. Mac client program

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

 

Iii. Unity client C # script

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.