有谁知道我可以在哪里获得一个开箱即用的工作示例,以便我可以通过代码并了解实现?
解决方法 基于socket.io的例子:服务器(index.Js,请参阅socket.io网站进行设置):
var app = require('express')();var http = require('http').Server(app);var io = require('socket.io')(http);app.get('/',function(req,res){ res.sendfile(__dirname + '/index.HTML');});io.on('connection',function(socket){ socket.on('chat message',function(msg){ io.emit('chat message',msg); });});http.Listen(8080,function(){ console.log('Listening on *:8080');});
客户端(VIEwController.swift):
import UIKitimport Socket_IO_ClIEnt_Swiftclass VIEwController: UIVIEwController {@IBOutlet weak var chatVIEw:UITextVIEw!@IBOutlet weak var sendbutton:UIbutton!@IBOutlet weak var sendFIEld:UITextFIEld!let socket = SocketIOClIEnt(socketURL: "10.0.0.1:8080",opts: ["log": true])overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() addHandlers() self.socket.connect()}@IBAction func send() { self.socket.emit("chat message",withItems: [self.sendFIEld.text!]) self.sendFIEld.text = ""}func addHandlers() { self.socket.on("connect") {data,ack in print("socket connected") } self.socket.on("chat message") {[weak self] data,ack in if let value = data.first as? String { self?.chatVIEw.text?.appendContentsOf(value + "\n") } }}}
Web客户端(index.HTML,对测试很有用):
<!DOCTYPE HTML><HTML> <head> <Title>Socket.IO chat</Title> <style> * { margin: 0; padding: 0; Box-sizing: border-Box; } body { Font: 13px Helvetica,Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; wIDth: 100%; } form input { border: 0; padding: 10px; wIDth: 90%; margin-right: .5%; } form button { wIDth: 9%; background: rgb(130,224,255); border: none; padding: 10px; } #messages { List-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul ID="messages"></ul> <form action=""> <input ID="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdn.socket.io/socket.io-1.2.0.Js"></script> <script src="http://code.jquery.com/jquery-1.11.1.Js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message',$('#m').val()); $('#m').val(''); return false; }); socket.on('chat message',function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body></HTML>总结
以上是内存溢出为你收集整理的ios – 后端使用Swift和Node.js的Socket.io示例全部内容,希望文章能够帮你解决ios – 后端使用Swift和Node.js的Socket.io示例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)