Компьютерные сети
1
Вклад в тег
package main
import (
"fmt"
"net"
)
func inet_aton(ip string) (ip_int uint32) {
ip_byte := net.ParseIP(ip).To4()
for i := 0; i < len(ip_byte); i++ {
ip_int |= uint32(ip_byte[i])
if i < 3 {
ip_int <<= 8
}
}
return
}
func inet_ntoa(ip uint32) string {
return fmt.Sprintf("%d.%d.%d.%d", byte(ip>>24), byte(ip>>16), byte(ip>>8),
byte(ip))
}
func main() {
ip0 := inet_aton("127.0.0.1")
ip1 := inet_aton("127.225.225.224")
diff := ip1 - ip0
var parts uint32 = 30
step := diff/parts
var ippps string = "0"
for i := uint32(0); i < parts; i++ {
//вместо принта шлю зону ботам
if ippps != "0"{
fmt.Println(ippps+"-"+inet_ntoa(ip0 + step*i))
}
ippps = inet_ntoa(ip0 + step*i)
}
}
package server
import (
"bufio"
"fmt"
"io"
"net"
"os"
)
func Run(host string, port string, handle func(data string) string) {
l, err := net.Listen("tcp", host+":"+port)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
defer l.Close()
fmt.Println("Слушает " + host + ":" + port)
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Ошибка запуска: ", err.Error())
os.Exit(1)
}
go handleRequest(conn, handle)
}
}
func handleRequest(conn net.Conn, handle func(data string) string) {
fmt.Println("handleRequest")
var (
buf = make([]byte, 1024)
r = bufio.NewReader(conn)
w = bufio.NewWriter(conn)
)
ILOOP:
for {
n, err := r.Read(buf)
data := string(buf[:n])
switch err {
case io.EOF:
break ILOOP
case nil:
if string(data) == "ConnectionClose" {
fmt.Println("Соединение закрыто")
w.WriteString("ConnectionClose\r\n")
w.Flush()
conn.Close()
} else {
w.WriteString(handle(data) + "\r\n")
w.Flush()
//break ILOOP
}
default:
fmt.Println("Ошибка при получении:", err)
break ILOOP
}
}
}
package client
import (
"bufio"
"fmt"
"io"
"net"
"strings"
)
type TcpClient struct {
r *bufio.Reader
w *bufio.Writer
buf []byte
conn net.Conn
}
func Connect(host string, port string) (TcpClient, error) {
fmt.Println("Connect")
conn, err := net.Dial("tcp", host+":"+port)
return TcpClient{
buf: make([]byte, 1024),
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
conn: conn,
}, err
}
func (tcp TcpClient) Send(dataSend string) (string, error) {
var (
returnData string
returnErr error
)
tcp.w.WriteString(dataSend + "\r\n")
tcp.w.Flush()
ILOOP:
for {
n, err := tcp.r.Read(tcp.buf)
data := string(tcp.buf[:n])
switch err {
case io.EOF:
break ILOOP
case nil:
returnData = data
returnErr = nil
if isTransportOver(data) {
break ILOOP
}
default:
returnData = ""
returnErr = err
}
}
return returnData, returnErr
}
func (tcp TcpClient) Close() {
tcp.conn.Close()
}
func isTransportOver(data string) (over bool) {
over = strings.HasSuffix(data, "\r\n")
return
}