func main() { flag.Parse() if len(*filename) == 0 { jklog.L().Errorln("I must know what file to do with ...") return } if *revert == false { todo := NewItoY("", "", "") err := todo.NewSaveWithDir(*filename, *saveposition) if err != nil && err != io.EOF { jklog.L().Errorln("err: ", err) return } } else { todo := NewItoY("", "", "") err := todo.NewSaveWithDirRevert(*filename, *saveposition) if err != nil && err != io.EOF { jklog.L().Errorln("error : ", err) return } } jklog.L().Infoln("Do it success ...") return }
func (debug *JKDeviceDebug) DoCommand(cmd, args string) string { err := debug.sendCommandOut(cmd, args) if err != nil { return "" } // wait the result of the data. var resultData string //t := time.Now() for { //now := time.Now() //v := now - t //if v > 5 { // break //} recvData := make([]byte, 1024) n, err := debug.conn.Read(recvData) if io.EOF == err { break } if err != nil { jklog.L().Errorln("read error : ", err) break } // resultData = make([]byte, n) // resultData = append(resultData, recvData[0:n]) if n > 0 { resultData += string(recvData[0:n]) } jklog.L().Infof("recv data [%s], len [%d]\n", recvData, n) break } return string(resultData) }
func (cm *JKConnectManager) JKSendUDPCommand(addr string, data string) error { if len(addr) <= 0 { addr = cm.FromAddr } ln, err := net.ResolveUDPAddr("udp", addr+":"+strconv.Itoa(JK_LISTEN_PORT)) if err != nil { jklog.L().Errorln("resolve udp fail of addr ", addr, " error :", err) return err } cn, err := net.DialUDP("udp", nil, ln) if err != nil { jklog.L().Errorln("Dial udp fail of addr ", addr, " error : ", err) return err } defer cn.Close() n, err := cn.Write([]byte(data)) if err != nil { jklog.L().Errorln("write to addr ", addr, " fail ", err) return err } jklog.L().Debugln("send out to ", addr, " data of len ", n) jklog.L().Debugln("send out data are : ", data) return nil }
func JKSaveFileData(id, filename, data string) bool { filepath := "./" + JK_SERVER_FILE_POSITION + "/" + id + "/" + filename prefix := os.Getenv("HOME") if len(prefix) > 0 { filepath = prefix + "/" + JK_SERVER_FILE_POSITION + "/" + id + "/" + filename } indx := strings.LastIndex(filepath, "/") if indx > 0 { dirs := filepath[0:indx] err := os.MkdirAll(dirs, os.ModePerm) if err != nil { jklog.L().Errorln("create dir failed: ", err) return false } } f, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) if err != nil { f, err = os.Create(filepath) if err != nil { jklog.L().Errorf("Open %s failed %v\n", filepath, err) return false } } defer f.Close() _, err = f.WriteString(data) if err != nil { jklog.L().Errorln("Write data failed: ", err) return false } return true }
// Parse start here, give one file or dir // It will check all file if give dir // @docsname: create what dir to save docs func JKParseDocStart(filename string, docsname string) { jklog.L().SetLevel(jklog.LEVEL_MUCH) jklog.L().Infoln("parse doc start ", filename) p := &JKParseDoc{} // create docsname if it is not exists. err := os.Mkdir(docsname, os.ModeDir) if err != nil { // docs not exists. os.Create(docsname) } p.prefix = docsname dir, err := os.Stat(filename) if err != nil { return } if dir.IsDir() { err = p.parse_dir_files(filename) if err != nil { jklog.L().Errorln("pasre dir : ", err) } // Only dir need generate index file p.generateIndexFile() } else { p.files = append(p.files, filename) } // p.Output() p.parse_files() jklog.L().Infoln("All done, exist...") }
func receiverAndOutResponse(listen, cmd string) { jklog.L().Infoln("Receiver data from [", listen, "] of file ", cmd) lListen, err := net.Listen("tcp", listen) if err != nil { return } defer lListen.Close() c, err := lListen.Accept() if err != nil { jklog.L().Errorln("Accept error : ", err) return } for { recvdata := make([]byte, 1024) // go func() { n, err := c.Read(recvdata) if io.EOF == err { time.Sleep(10 * time.Microsecond) break } if err != nil { jklog.L().Errorln("read error : ", err) break } jklog.L().Infof("recv data [%s], len [%d]\n", recvdata, n) } }
func jk_send_query(addr string) { jklog.L().Infoln("Start to connect to ", addr) _, err := net.Dial("tcp", addr+":"+strconv.Itoa(JK_CONNECT_TO_PORT)) if err != nil { jklog.L().Errorln("Dial fail of ", addr+":"+strconv.Itoa(JK_CONNECT_TO_PORT), " ", err) return } }
func main() { v := 231 buf := BytesToInt(int64(v), 4) jklog.L().Infoln("buf: ", buf) v1 := IntToBytes(buf) jklog.L().Infoln("int: ", int(v1)) }
func jk_dial_udp_ext_data(mac, ip string, port int, cmdType int, dlen int, dstring string) error { // start to send command to everywhere through udp ser, err := net.ResolveUDPAddr("udp", ip+":"+strconv.Itoa(port)) if err != nil { return err } // jklog.L().Infoln("dial udp ", ser.IP, ser.Port, ser.Zone, ser.Network(), ser.String()) dialout, err := net.DialUDP("udp", nil, ser) if err != nil { return err } // version dstmac srcmac sessionid dataid cmdtype datalen data // inmac := []byte(mac) lm := jk_get_mac_addr() jklog.L().Infoln("The mac addr ", lm) b_buf := bytes.NewBuffer([]byte{}) binary.Write(b_buf, binary.LittleEndian, int32(cmdType)) cmdbuf := b_buf.Bytes() // jklog.L().Infoln("cmd type ", cmdType, ", b_buf ", cmdbuf) dlenbuf := []byte{0, 0, 0, 0} if dlen > 0 { binary.Write(b_buf, binary.LittleEndian, int32(dlen)) dlenbuf = b_buf.Bytes() } // 00 00 00 00 ff ff ff ff ff ff 00 0d 60 dc c3 d3 74 65 6d 70 00 00 00 80 01 00 00 00 00 00 00 00 sendstr := []byte{ 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, lm[0], lm[1], lm[2], lm[3], lm[4], lm[5], 0x4, 0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x80, cmdbuf[0], cmdbuf[1], cmdbuf[2], cmdbuf[3], dlenbuf[0], dlenbuf[1], dlenbuf[2], dlenbuf[3], } if dlen > 0 { dialout.Write(sendstr) } else { v := []byte(dstring) for _, t := range v { sendstr = append(sendstr, t) } dialout.Write(sendstr) } jklog.L().Debugln("send string to udp ", port, " down!") dialout.Close() return nil }
func (debug *JKDeviceDebug) sendCommandOut(cmd, args string) error { sendData := cmd + "[" + args + "]" n, err := debug.conn.Write([]byte(sendData)) if err != nil { jklog.L().Errorln("write command failed ", sendData, " with error ", err) return err } else { jklog.L().Infoln("write done data ", sendData, " with len ", n) } return nil }
/** return len of write */ func (s *SmartEye) WriteRequest(value string) int { if s.conn == nil { jklog.L().Errorln("no connect") return 0 } w, err := s.conn.Write([]byte(value + "\r\n")) if err == nil { return w } jklog.L().Errorln("write error : ", err) return 0 }
func (c *KFClient) startClient(addr string, port int) bool { c.handle = cli.JKNewClientNew(addr, port) reconn: ret := c.handle.CliConnect(0, true) if !ret { return false } // tmstr := fmt.Sprintf("%d", time.Now().Unix()) p := NewJKProtocol() regstr := p.GenerateRegister(*id) n, err := c.handle.Write([]byte(regstr)) if err != nil { jklog.L().Errorln("write failed: ", err) goto reconn } jklog.L().Debugln("write done of len: ", n) itemData := &cli.JKClientItem{} n, err = c.handle.Read(itemData) if err != nil { jklog.L().Errorln("read failed, ", err) } else { jklog.L().Infoln("read data: ", string(itemData.Data)) } var startTime int64 for { now := time.Now().Unix() if now-startTime < 300 { time.Sleep(time.Millisecond * 1000) continue } startTime = now wstr := p.GenerateControlSaveFile(*id+".log", "Hello, I'm online - "+time.Now().String()) _, err = c.handle.Write([]byte(wstr)) if err != nil { jklog.L().Errorln("write failed, ", err) goto reconn } } c.handle.Close() return true }
func main() { flag.Parse() http.Handle("/", http.FileServer(http.Dir(*dir))) inPort := *port if inPort[0] != ':' { inPort = ":" + inPort } jklog.L().Infof("Start server in %s with local %s\n", inPort, *dir) http.ListenAndServe(inPort, nil) jklog.L().Errorln("Failed listen in %s with local %s\n", inPort, *dir) }
/** read data, read 1024 every time * return read len */ func (s *SmartEye) Read(buf []byte) int { if s.conn == nil { jklog.L().Errorln("no connect") return 0 } buf = make([]byte, 1024) l, err := s.conn.Read(buf) if err == nil { return l } jklog.L().Errorln("read error : ", err) return 0 }
func ExampleScrape() { doc, err := goquery.NewDocument("http://www.rfcreader.com/#rfc3550") // doc, err := goquery.NewDocument("http://192.168.6.151") if err != nil { jklog.L().Errorln("error open the document:", err) } table := doc.Find("div") value := table.Text() jklog.L().Infoln("the table: ", value) // doc.Find("table").Each(func(i int, s *goquery.Selection) { // jklog.L().Infof("Review %d: %s \n", i, s.Text()) // }) }
func jk_listen_udp_msg(port int) error { // // start to listen response command // jklog.L().Infoln("listen udp addr " + strconv.Itoa(port)) addrs, err := net.InterfaceAddrs() if err != nil { return err } var localAddr string for _, t := range addrs { if strings.HasPrefix(t.String(), "192.168") { localAddr = t.String() } } jklog.L().Debugln("listen to ", localAddr, ":", strconv.Itoa(port)) service, err := net.ResolveUDPAddr("udp4", ":"+strconv.Itoa(port)) if err != nil { return err } waitresp, err = net.ListenUDP("udp", service) if err != nil { return err } go func() { for { buf := make([]byte, 512) n, _, err := waitresp.ReadFromUDP(buf) if err != nil { // jklog.L().Errorln("read from udp ", err) break } if n == 0 { time.Sleep(500 * time.Microsecond) } else { // jklog.L().Infoln("out recv -- ", n, addr) // waitresp.WriteToUDP([]byte("get message send response"), addr) jk_deal_response(buf[:n]) } } // jklog.L().Errorln("shouldn't down here") }() return nil }
func (en *JKEncoderImage) JK_reducejpeg(save, name string, enType draw.Op, quality int) error { // 1. Open file ifile, err := os.Open(name) if err != nil { return err } defer ifile.Close() // Create file to save ofile, err := os.Create(save) if err != nil { return err } defer ofile.Close() /* config, err := jpeg.DecodeConfig(ifile) if err != nil { jklog.L().Errorln("error : ", err) } jklog.L().Infof("[%d, %d]\n", config.Width, config.Height) */ img, err := jpeg.Decode(ifile) if err != nil { jklog.L().Errorln("error : ", err) return err } bounds := img.Bounds() x := bounds.Dx() y := bounds.Dy() nx := x * en.Scale / 100 ny := y * en.Scale / 100 m := image.NewRGBA(image.Rect(0, 0, x, y)) jklog.L().Infof("[%d, %d] \n", x, y) // white := color.RGBA{255, 255, 255, 255} // draw.Draw(m, bounds, &image.Uniform{white}, image.ZP, draw.Src) // draw.Draw(m, bounds, img, image.ZP, draw.Src) draw.Draw(m, m.Bounds(), img, bounds.Min, enType) mm := image.NewRGBA(image.Rect(0, 0, nx, ny)) graphics.Scale(mm, m) err = jpeg.Encode(ofile, mm, &jpeg.Options{quality}) if err != nil { jklog.L().Errorln("error: ", err) return err } return nil }
func ParseDataResponse(h JK_P_Header, data string) { mCmd := h.GetMainCommand() sCmd := h.GetSlaveCommand() jklog.L().Debugln("response ", mCmd, "/", sCmd) switch mCmd { case JK_P_CMD_DEVICE_CONNECT: switch sCmd { case JK_P_CMD_DEVICE_CONNECT_QUERY: jklog.L().Infoln("data is : ", data) case JK_P_CMD_DEVICE_CONNECT_FILE_TRANSFER: } } }
func writeDataToFile(buf []byte) { filename := "c:/Users/v-jmd/Desktop/mediafrom-ios" f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeDir) if err != nil { jklog.L().Errorln("open failed ", filename) return } cnts, err := f.WriteString(string(buf)) if err != nil { jklog.L().Errorln("write to file error ", err) return } jklog.L().Infoln("Write ", cnts) f.Close() }
// Parse One file and write to html func (p *JKParseDoc) parse_one_file(filename string) error { ph, err := parse_header_file(filename) if err != nil { jklog.L().Errorln("parse error : ", err) return err } // p.PrintOut() jklog.L().Infoln("Write to file ", filename, " ...") ph.SetPrefix(p.prefix) err = ph.WriteToHtml() if err != nil { return err } return nil }
func (newser *JKNewServer) Read(proc *JKServerProcess, procItem *JKServerProcessItem) (int, error) { servItem := procItem remAddr := procItem.Conn.RemoteAddr().String() servItem.RemoteAddr = remAddr proc.addItem(servItem) jklog.L().Debugln("first read first bytes.") // first read 4 bytes for length. buflen := make([]byte, 4) _, err := procItem.Conn.Read(buflen) if err != nil { jklog.Lfile().Errorln("read failed of first read. ", err) return 0, err } datalen := int(BytesToInt(buflen)) jklog.L().Debugln("length of after data: ", datalen) readbuf := make([]byte, datalen) lenbuf := 0 jklog.L().Debugln("goto read data from : ", remAddr) for { if lenbuf >= datalen { procItem.ReadDone <- true break } buf := make([]byte, 1024) n, err := procItem.Conn.Read(buf) if err == io.EOF { jklog.Lfile().Infoln("EOF of read.") break } if err != nil { jklog.Lfile().Errorln("read data failed: ", err) return 0, err } copy(readbuf[lenbuf:lenbuf+n], buf[0:n]) lenbuf += n servItem.Data = readbuf } // procItem.ReadDone <- true jklog.L().Infoln("data from ", procItem.RemoteAddr, " with len ", lenbuf) return lenbuf, nil }
func MongoWindow(parent walk.Window) { mw := &MongoWin{lsName: newListName()} main := MainWindow{ AssignTo: &mw.MainWindow, Title: "数据库", MinSize: Size{400, 280}, Layout: VBox{}, Children: []Widget{ VSplitter{ Children: []Widget{ ListBox{ AssignTo: &mw.lb, Model: mw.lsName, }, }, }, }, } err := main.Create() if err != nil { jklog.L().Fatal(err) } mw.Run() }
func main() { l := jklog.L() l.Noneln("============parse addr=============") if len(os.Args) != 2 { l.Fatalf("Usage: %s ip-addr/host\n", os.Args[0]) } // socket.PrintAllSenderHeader(socket.GetResponse(os.Args[1])) l.Noneln("next") // socket.PrintAllHeader(socket.GetResponse(os.Args[1])) //str := socket.GetResponseBody(os.Args[1]) //fmt.Println(str) //str, _ := socket.GetAddrsHosts(os.Args[1]) return // l.Noneln("start to list") // list.MyList() // mymap.MyMap() l.Noneln("========= test web socket ========") http.Handle("/", websocket.Handler(socket.WebSocket)) if err := http.ListenAndServe(":1234", nil); err != nil { l.Fatalln("ListAndServe: ", err) } }
func NetWindow(parent walk.Window) { /** some init */ mw := new(NetWin) /* init main windows element */ main := MainWindow{ AssignTo: &mw.MainWindow, Title: "SmartEye Client", MinSize: Size{600, 480}, Layout: VBox{}, Children: []Widget{ TextEdit{ AssignTo: &mw.input, }, PushButton{ AssignTo: &mw.submit, Text: "发送", OnClicked: mw.sendAndResp, }, TextEdit{ AssignTo: &mw.display, ReadOnly: true, }, }, } err := main.Create() if err != nil { jklog.L().Fatal(err) } mw.Run() }
func PrintAllSenderHeader(res *http.Response) { l := jklog.L() l.Noneln("Send header") for k, v := range res.Request.Header { l.Infoln(k, ": ", v) } }
func TgdzOut(parent walk.Window) { mw := new(tgdzWindow) main := MainWindow{ AssignTo: &mw.MainWindow, Title: "天干地支年结果", MinSize: Size{400, 320}, Layout: VBox{}, Children: []Widget{ TextEdit{ AssignTo: &mw.inputYear, // ReadOnly: true, }, PushButton{ AssignTo: &mw.submit, Text: "查查看", OnClicked: mw.giveResult, }, TextEdit{ AssignTo: &mw.outputResult, ReadOnly: true, }, }, } err := main.Create() if err != nil { jklog.L().Fatal(err) } mw.Run() }
func (s *KFServer) startServer() bool { ret := s.handle.Start(&s.proc) if !ret { jklog.Lfile().Errorln("failed start server.") return false } for { jklog.L().Infoln("wait accept. ") jklog.Lfile().Infoln("wait accept. ") c := s.handle.Accept(&s.proc) if c == nil { jklog.Lfile().Errorln("accept failed.") return false } item := &sv.JKServerProcessItem{} item.Conn = c item.ReadDone = make(chan bool) go s.dealResponse(s.proc, item) go func() bool { for { _, err := s.handle.Read(&s.proc, item) if err != nil { item.ReadDone <- false return false } } return true }() } jklog.Lfile().Errorln("Program return for failed start.") return true }
// @param filename Absolute name include the path func (iy *ItoY) OpenAndSaveToNew(filename string, savelocation string) error { if filename[0] == '.' { return nil } // Open file and prepare to close fin, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm) if err != nil { return err } defer fin.Close() var writefilename = savelocation _, err = os.Stat(writefilename) var fout *os.File if os.IsNotExist(err) { fout, err = os.Create(writefilename) } else { fout, err = os.OpenFile(writefilename, os.O_APPEND|os.O_RDWR, os.ModePerm) } if err != nil { jklog.L().Errorln("open error ", err) return err } defer fout.Close() err = iy.readAndWrite(fin, fout) if err != nil { return err } return nil }
func sendDataOut(c net.Conn, name string) { if name == "" { jklog.L().Errorln("give me some name [fullpath]") return } f, err := os.OpenFile(name, os.O_RDONLY, os.ModePerm) if err != nil { jklog.L().Errorln("err open file ", name) return } sendFilename := name i := strings.LastIndex(name, "/") if i >= 0 { sendFilename = name[i+1 : len(name)] } c.Write([]byte("filename\n" + sendFilename)) jklog.L().Infoln("send out ==> filename:", sendFilename) max := 0 go func() { lastvalue := 0 tCnts := 1 for { if max == -1 { jklog.L().Infoln("The av send speed ", lastvalue/tCnts/1000000, "Mb/s") break } jklog.L().Infoln("Send Data Out", max, "(", (max-lastvalue)/5/1000000, "Mb/s)") lastvalue = max time.Sleep(5000 * time.Millisecond) tCnts += 5 } }() buf := make([]byte, onceLen) for { cnts, err := f.Read(buf) if err != nil { jklog.L().Errorln("read err ==>", err) break } // jklog.L().Infoln("read out len ", cnts) wlen, err := c.Write(buf[0:cnts]) if err != nil { jklog.L().Errorln("write err ==>", err) break } max += wlen // jklog.L().Infoln("write down ", wlen) } f.Close() jklog.L().Infoln("transfered len ", max, "of file", name) max = -1 }
func receiverAndOutValue(conn net.Conn) { jklog.L().Infoln("Receiver data from [", conn.LocalAddr().String(), "]") for { recvData := make([]byte, 1024) n, err := conn.Read(recvData) if io.EOF == err { break } if err != nil { jklog.L().Errorln("read error : ", err) break } jklog.L().Infof("recv data [%s], len [%d]\n", recvData, n) break } }