-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
275 lines (236 loc) · 5.62 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"bufio"
"fmt"
"net"
"os/user"
"strings"
"sync"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/driver/desktop"
"fyne.io/fyne/v2/widget"
)
type User struct {
Addr string
Name string
}
var (
users = make(map[string]User)
mutex = &sync.Mutex{}
chatLogView *widget.List
input *widget.Entry
usersList *widget.List
username = ""
broadcast = "192.168.10.255:9999"
localPort = ":9999"
tcpPort = ":8080"
selectedIP string
myApp fyne.App
myWindow fyne.Window
chatList binding.StringList
)
func main() {
currentUser, err := user.Current()
if err != nil {
fmt.Println("Error getting current user:", err)
return
}
username = currentUser.Username
myApp = app.NewWithID("com.wimbot.app")
myWindow = myApp.NewWindow("P2PChat")
//init chat history
chatList = binding.NewStringList()
input = widget.NewEntry()
input.SetPlaceHolder("Type your message here...")
chatLogView = widget.NewListWithData(chatList,
func() fyne.CanvasObject {
return widget.NewLabel("template")
},
func(i binding.DataItem, o fyne.CanvasObject) {
o.(*widget.Label).Bind(i.(binding.String))
})
chatLogContainer := container.NewGridWrap(fyne.NewSize(300, 300), chatLogView)
usersList = widget.NewList(
func() int {
return len(users)
},
func() fyne.CanvasObject {
return widget.NewLabel("User")
},
func(i int, item fyne.CanvasObject) {
mutex.Lock()
defer mutex.Unlock()
keys := make([]string, 0, len(users))
for k := range users {
keys = append(keys, k)
}
user := users[keys[i]]
item.(*widget.Label).SetText(user.Name + " (" + user.Addr + ")")
})
usersList.OnSelected = func(id widget.ListItemID) {
mutex.Lock()
defer mutex.Unlock()
keys := make([]string, 0, len(users))
for k := range users {
keys = append(keys, k)
}
selectedIP = keys[id]
}
sendButton := widget.NewButton("Send", func() {
message := input.Text
if message != "" && selectedIP != "" {
sendMessage(selectedIP, message)
input.SetText("")
} else {
dialog.ShowInformation("Error", "Please select a user and enter a message", myWindow)
}
})
userListContainer := container.NewScroll(usersList)
userListContainer.SetMinSize(fyne.NewSize(300, 200))
if desk, ok := myApp.(desktop.App); ok {
m := fyne.NewMenu("MyApp",
fyne.NewMenuItem("Show", func() {
myWindow.Show()
}))
desk.SetSystemTrayMenu(m)
iconData, err := fyne.LoadResourceFromPath("icon.ico")
if err != nil {
fmt.Println("Error loading icon:", err)
return
}
desk.SetSystemTrayIcon(iconData)
}
content := container.NewVBox(
userListContainer,
chatLogContainer,
input,
sendButton,
)
myWindow.SetContent(content)
myWindow.SetCloseIntercept(func() {
myWindow.Hide()
})
// Start UDP broadcasting and listening
go startBroadcasting()
go listenForBroadcasts()
// Start TCP server for direct messaging
go startTCPServer()
myApp.Run()
}
// Broadcast presence to the network
func startBroadcasting() {
addr, err := net.ResolveUDPAddr("udp", broadcast)
if err != nil {
fmt.Println("Error resolving UDP address:", err)
return
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
fmt.Println("Error dialing UDP:", err)
return
}
defer conn.Close()
for {
message := username + "@" + tcpPort
_, err := conn.Write([]byte(message))
if err != nil {
fmt.Println("Error broadcasting:", err)
}
time.Sleep(5 * time.Second)
}
}
// Listen for broadcasts from other users
func listenForBroadcasts() {
addr, err := net.ResolveUDPAddr("udp", localPort)
if err != nil {
fmt.Println("Error resolving UDP address:", err)
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println("Error listening on UDP:", err)
return
}
defer conn.Close()
buffer := make([]byte, 1024)
for {
n, remoteAddr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading from UDP:", err)
continue
}
data := strings.Split(string(buffer[:n]), "@")
if len(data) != 2 {
continue
}
name := data[0]
tcpAddress := remoteAddr.IP.String() + data[1]
mutex.Lock()
users[tcpAddress] = User{
Addr: tcpAddress,
Name: name,
}
mutex.Unlock()
usersList.Refresh()
}
}
// Start TCP server for receiving direct messages
func startTCPServer() {
listener, err := net.Listen("tcp", tcpPort)
if err != nil {
fmt.Println("Error starting TCP server:", err)
return
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleTCPConnection(conn)
}
}
// Handle incoming TCP connections
func handleTCPConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading from connection:", err)
return
}
displayMessage(message)
myApp.SendNotification(&fyne.Notification{
Title: "New Message",
Content: message,
})
}
// Send message to selected user
func sendMessage(addr, message string) {
conn, err := net.Dial("tcp", addr)
if err != nil {
fmt.Println("Error connecting to peer:", err)
return
}
defer conn.Close()
writer := bufio.NewWriter(conn)
writer.WriteString(message + "\n")
writer.Flush()
displayMessage("Me: " + message)
}
// Display a message in the chat log
func displayMessage(message string) {
length := chatList.Length()
if length >= 100 {
// Remove the first element by setting a new slice without it
existing, _ := chatList.Get()
chatList.Set(existing[1:])
}
chatList.Append(message)
}