You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

socket.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016- Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "bufio"
  7. "io"
  8. "net"
  9. "strings"
  10. )
  11. // Socket represents an IRC socket.
  12. type Socket struct {
  13. Closed bool
  14. conn net.Conn
  15. reader *bufio.Reader
  16. }
  17. // NewSocket returns a new Socket.
  18. func NewSocket(conn net.Conn) Socket {
  19. return Socket{
  20. conn: conn,
  21. reader: bufio.NewReader(conn),
  22. }
  23. }
  24. // Close stops a Socket from being able to send/receive any more data.
  25. func (socket *Socket) Close() {
  26. if socket.Closed {
  27. return
  28. }
  29. socket.Closed = true
  30. socket.conn.Close()
  31. }
  32. // Read returns a single IRC line from a Socket.
  33. func (socket *Socket) Read() (string, error) {
  34. if socket.Closed {
  35. return "", io.EOF
  36. }
  37. lineBytes, err := socket.reader.ReadBytes('\n')
  38. // convert bytes to string
  39. line := string(lineBytes[:])
  40. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  41. if err == io.EOF {
  42. socket.Close()
  43. }
  44. if err == io.EOF && strings.TrimSpace(line) != "" {
  45. // don't do anything
  46. } else if err != nil {
  47. return "", err
  48. }
  49. return strings.TrimRight(line, "\r\n"), nil
  50. }
  51. // Write sends the given string out of Socket.
  52. func (socket *Socket) Write(data string) error {
  53. if socket.Closed {
  54. return io.EOF
  55. }
  56. // write data
  57. _, err := socket.conn.Write([]byte(data))
  58. if err != nil {
  59. socket.Close()
  60. return err
  61. }
  62. return nil
  63. }
  64. // WriteLine writes the given line out of Socket.
  65. func (socket *Socket) WriteLine(line string) error {
  66. return socket.Write(line + "\r\n")
  67. }