添加聊天工具项目的基本结构和功能实现,包括用户认证、消息处理、文件传输及数据库操作
This commit is contained in:
BIN
chat_project/client/client
Normal file
BIN
chat_project/client/client
Normal file
Binary file not shown.
59
chat_project/client/file_transfer.go
Normal file
59
chat_project/client/file_transfer.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
)
|
||||
|
||||
// 客户端接收文件的示例函数
|
||||
func ReceiveFile(conn net.Conn, filename string, filesize int64) error {
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var received int64 = 0
|
||||
buf := make([]byte, 4096)
|
||||
for received < filesize {
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return err
|
||||
}
|
||||
file.Write(buf[:n])
|
||||
received += int64(n)
|
||||
}
|
||||
fmt.Printf("文件 %s 接收完成,共 %d 字节\n", filename, received)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 客户端发送文件的示例函数
|
||||
func SendFile(conn net.Conn, filepath string) error {
|
||||
file, err := os.Open(filepath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
n, err := file.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return err
|
||||
}
|
||||
_, err = conn.Write(buf[:n])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Printf("文件 %s 发送完成\n", filepath)
|
||||
return nil
|
||||
}
|
50
chat_project/client/main.go
Normal file
50
chat_project/client/main.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
conn, err := net.Dial("tcp", "127.0.0.1:8888")
|
||||
if err != nil {
|
||||
log.Fatalf("无法连接服务器: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
fmt.Println("已连接到服务器 127.0.0.1:8888")
|
||||
|
||||
// 启动协程接收服务器消息
|
||||
go func() {
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
log.Printf("读取服务器消息错误: %v", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
fmt.Printf("服务器消息: %s\n", string(buf[:n]))
|
||||
}
|
||||
}()
|
||||
|
||||
// 从命令行读取输入并发送给服务器
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for {
|
||||
fmt.Print("请输入消息: ")
|
||||
if !scanner.Scan() {
|
||||
break
|
||||
}
|
||||
text := scanner.Text()
|
||||
if text == "exit" {
|
||||
fmt.Println("退出客户端")
|
||||
break
|
||||
}
|
||||
_, err := conn.Write([]byte(text))
|
||||
if err != nil {
|
||||
log.Printf("发送消息失败: %v", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user