Skip to content

mpartio/SwiftSocket

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

a simple socket library for apple swift lang

useage

drag ysocket.c and ysocket.swift to your project just use apis in YSocket class

api usage

create client socket

	//create a socket connect to www.apple.com and port at 80
	var client:TCPClient = TCPClient(addr: "www.apple.com", port: 80)

connect with timeout

var (success,errmsg)=client.connect(timeout: 10)

send data

var (success,errmsg)=client.send(str:"GET / HTTP/1.0\n\n" )
//or you can send binnary data
//socket.send(data:[Int8])

read data

var data=client.read(1024*10) //return optional [Int8]

close socket

var (success,errormsg)=client.close()

create servert socket

var server:TCPServer = TCPServer(addr: "127.0.0.1", port: 8080)

listen

var (success,msg)=server.listen()

accept

var client=server.accept() //now you can use client socket api to read and write

client socket example

//创建socket
var client:TCPClient = TCPClient(addr: "www.apple.com", port: 80)
//连接
var (success,errmsg)=client.connect(timeout: 1)
if success{
    //发送数据
    var (success,errmsg)=client.send(str:"GET / HTTP/1.0\n\n" )
    if success{
        //读取数据
        var data=client.read(1024*10)
        if let d=data{
            if let str=String.stringWithBytes(d, length: d.count, encoding: NSUTF8StringEncoding){
                println(str)
            }
        }
    }else{
        println(errmsg)
    }
}else{
    println(errmsg)
}

server socket excample(echo server)

func echoService(client c:TCPClient){
    println("newclient from:\(c.addr)[\(c.port)]")
    var d=c.read(1024*10)
    c.send(data: d!)
    c.close()
}
func testserver(){
    var server:TCPServer = TCPServer(addr: "127.0.0.1", port: 8080)
    var (success,msg)=server.listen()
    if success{
        while true{
            if var client=server.accept(){
                echoService(client: client)
            }else{
                println("accept error")
            }
        }
    }else{
        println(msg)
    }
}

Copyright and License

Code released under the BSD license.

QQ group

275935304

About

simple socket library for apple swift lang.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 63.0%
  • C 33.5%
  • Objective-C 3.5%