Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Simple LAN Chat between two PCs on the same network
- .DESCRIPTION
- Enables two-way communication between computers using TCP sockets
- PC NAMES AND IPs:
- staaandup 192.168.1.101
- inferno 192.168.1.105
- .PARAMETER RemoteIP
- IP address of the other computer (default: 192.168.1.101)
- .PARAMETER Port
- Port number to use for communication (default: 5050)
- .PARAMETER UserName
- Your display name in chat (default: current username)
- .EXAMPLE
- .\LAN-Chat.ps1 -RemoteIP "192.168.1.105" -Port 5050 -UserName "Staaandup"
- #>
- param(
- [Parameter(Mandatory=$false)]
- [string]$RemoteIP = "192.168.1.101",
- [Parameter(Mandatory=$false)]
- [int]$Port = 5050,
- [Parameter(Mandatory=$false)]
- [string]$UserName = $env:USERNAME
- )
- # Load required assemblies
- Add-Type -AssemblyName System.Windows.Forms
- Add-Type -AssemblyName System.Drawing
- # Function to find an available port
- function Get-AvailablePort {
- param([int]$StartPort = 5050)
- $port = $StartPort
- $maxPort = $StartPort + 100 # Try up to 100 ports above the starting port
- while ($port -le $maxPort) {
- $tcpListener = $null
- try {
- $tcpListener = [System.Net.Sockets.TcpListener]::new($port)
- $tcpListener.Start()
- $tcpListener.Stop()
- return $port
- } catch {
- $port++
- } finally {
- if ($tcpListener) { $tcpListener.Stop() }
- }
- }
- return $null
- }
- # Function to kill any leftover listener jobs
- function Clear-StaleListeners {
- $staleJobs = Get-Job -Name "LANChatListener_*" -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Running' }
- foreach ($job in $staleJobs) {
- Write-Host "Cleaning up stale listener job: $($job.Name)" -ForegroundColor Yellow
- $job.StopJob()
- Remove-Job $job -Force
- }
- }
- # Clean up stale jobs before starting
- Clear-StaleListeners
- # Check if the port is available and find an alternative if needed
- $originalPort = $Port
- $availablePort = Get-AvailablePort -StartPort $Port
- if (-not $availablePort) {
- Write-Host "ERROR: No available ports found in range $Port-$($Port+100)!" -ForegroundColor Red
- Write-Host "Please close other applications and try again." -ForegroundColor Yellow
- exit 1
- }
- if ($availablePort -ne $originalPort) {
- Write-Host "Port $originalPort is in use. Using alternative port: $availablePort" -ForegroundColor Yellow
- $Port = $availablePort
- }
- # Create a unique identifier for this session
- $sessionID = Get-Random -Maximum 99999
- $global:listenerRunning = $true
- $global:cleanupDone = $false
- # Setup Ctrl+C handler
- [Console]::TreatControlCAsInput = $true
- # Clear console and show welcome screen initially
- Clear-Host
- Write-Host "============================================================" -ForegroundColor DarkCyan
- Write-Host " LAN CHAT - Connected as: $UserName" -ForegroundColor Cyan
- Write-Host "============================================================" -ForegroundColor DarkCyan
- Write-Host "Remote PC IP: $RemoteIP" -ForegroundColor Yellow
- Write-Host "Local Port: $Port" -ForegroundColor Yellow
- if ($Port -ne $originalPort) {
- Write-Host "(Original port $originalPort was in use)" -ForegroundColor DarkYellow
- }
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- Write-Host "Quick IP Reference:" -ForegroundColor Cyan
- Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
- Write-Host " inferno = 192.168.1.105" -ForegroundColor White
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- Write-Host "Type your messages below and press Enter to send." -ForegroundColor Green
- Write-Host "Type '/quit' to exit, '/clear' to clear screen" -ForegroundColor Green
- Write-Host "Type '/port' to see current port, '/ips' to show IP reference" -ForegroundColor Green
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- Write-Host "Starting listener on port $Port..." -ForegroundColor Green
- # Start listener in a background job with better error handling
- $scriptBlock = {
- param($localPort, $userName)
- Add-Type -AssemblyName System.Windows.Forms
- Add-Type -AssemblyName System.Drawing
- $listener = $null
- $running = $true
- try {
- # Create listener with reuse address option
- $listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $localPort)
- $listener.Server.SetSocketOption('Socket', 'ReuseAddress', 1)
- $listener.Start()
- $listener.Server.ReceiveTimeout = 1000
- # Signal that listener started successfully
- Write-Host "LISTENER_READY: $localPort"
- while ($running) {
- try {
- # Check if we can accept connections
- if ($listener.Pending()) {
- $client = $listener.AcceptTcpClient()
- $client.ReceiveTimeout = 5000
- $stream = $client.GetStream()
- $reader = New-Object System.IO.StreamReader($stream)
- # Read message
- $msg = $reader.ReadLine()
- if ($msg) {
- $timeStamp = Get-Date -Format "HH:mm:ss"
- # Parse message (format: "UserName: Message" or just raw message)
- if ($msg -match "^(.*?):(.*)$") {
- $senderName = $matches[1].Trim()
- $actualMessage = $matches[2].Trim()
- } else {
- $senderName = "Friend"
- $actualMessage = $msg
- }
- # Display message in console
- Write-Host "[$timeStamp] " -NoNewline
- Write-Host "$senderName" -ForegroundColor Cyan -NoNewline
- Write-Host ": $actualMessage"
- # Show balloon notification
- try {
- $notify = New-Object System.Windows.Forms.NotifyIcon
- $notify.Icon = [System.Drawing.SystemIcons]::Information
- $notify.Visible = $true
- $notify.ShowBalloonTip(3000, "LAN Chat - Message from $senderName", $actualMessage, [System.Windows.Forms.ToolTipIcon]::Info)
- Start-Sleep -Milliseconds 100
- $notify.Dispose()
- } catch {
- # Notifications might fail in some environments, ignore
- }
- }
- $client.Close()
- } else {
- Start-Sleep -Milliseconds 100
- }
- } catch {
- # Check if this is just a timeout or actual error
- if ($_.Exception.Message -notlike "*timeout*") {
- Write-Host "Error in listener: $($_.Exception.Message)" -ForegroundColor Red
- }
- }
- }
- } catch {
- Write-Host "FATAL LISTENER ERROR: $($_.Exception.Message)" -ForegroundColor Red
- } finally {
- if ($listener) {
- try {
- $listener.Stop()
- } catch {}
- }
- }
- }
- $listenerJob = Start-Job -Name "LANChatListener_$sessionID" -ScriptBlock $scriptBlock -ArgumentList $Port, $UserName
- # Wait for listener to start - simplified to avoid false warnings
- $timeout = 5
- $listenerStarted = $false
- while ($timeout -gt 0 -and -not $listenerStarted) {
- Start-Sleep -Milliseconds 500
- $jobOutput = Receive-Job $listenerJob -ErrorAction SilentlyContinue
- if ($jobOutput -match "LISTENER_READY") {
- $listenerStarted = $true
- Write-Host "Listener started successfully on port $Port" -ForegroundColor Green
- }
- $timeout--
- }
- if (-not $listenerStarted) {
- Write-Host "Note: Listener is starting in background." -ForegroundColor Yellow
- }
- # Function to send message
- function Send-Message {
- param([string]$Message)
- if ([string]::IsNullOrWhiteSpace($Message)) {
- return $true
- }
- # Check for commands
- switch ($Message) {
- '/quit' { return $false }
- '/clear' {
- Clear-Host
- # Redisplay header
- Write-Host "============================================================" -ForegroundColor DarkCyan
- Write-Host " LAN CHAT - Connected as: $UserName" -ForegroundColor Cyan
- Write-Host "============================================================" -ForegroundColor DarkCyan
- Write-Host "Remote PC IP: $RemoteIP" -ForegroundColor Yellow
- Write-Host "Local Port: $Port" -ForegroundColor Yellow
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- Write-Host "Quick IP Reference:" -ForegroundColor Cyan
- Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
- Write-Host " inferno = 192.168.1.105" -ForegroundColor White
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- Write-Host "Type your messages below and press Enter to send." -ForegroundColor Green
- Write-Host "Type '/quit' to exit, '/clear' to clear screen" -ForegroundColor Green
- Write-Host "Type '/port' to see current port, '/ips' to show IP reference" -ForegroundColor Green
- Write-Host "------------------------------------------------------------" -ForegroundColor DarkGray
- return $true
- }
- '/port' {
- Write-Host "Local port: $Port" -ForegroundColor Cyan
- return $true
- }
- '/ips' {
- Write-Host "IP Reference:" -ForegroundColor Cyan
- Write-Host " staaandup = 192.168.1.101" -ForegroundColor White
- Write-Host " inferno = 192.168.1.105" -ForegroundColor White
- return $true
- }
- }
- # Format message with username
- $formattedMessage = "$UserName`: $Message"
- $timeStamp = Get-Date -Format "HH:mm:ss"
- try {
- # Try to send message with retry logic
- $maxRetries = 2
- $retryCount = 0
- $sent = $false
- while (-not $sent -and $retryCount -lt $maxRetries) {
- try {
- $client = New-Object System.Net.Sockets.TcpClient
- $client.Connect($RemoteIP, $Port)
- $client.SendTimeout = 3000
- $writer = New-Object System.IO.StreamWriter($client.GetStream())
- $writer.AutoFlush = $true
- $writer.WriteLine($formattedMessage)
- $client.Close()
- $sent = $true
- # Display sent message
- Write-Host "[$timeStamp] " -ForegroundColor DarkGray -NoNewline
- Write-Host "You" -ForegroundColor Green -NoNewline
- Write-Host ": $Message" -ForegroundColor White
- } catch {
- $retryCount++
- if ($retryCount -ge $maxRetries) {
- throw
- }
- Start-Sleep -Milliseconds 200
- }
- }
- } catch {
- Write-Host "[$timeStamp] Could not send message: $($_.Exception.Message)" -ForegroundColor Red
- Write-Host " Make sure the other PC is running the chat script on port $Port" -ForegroundColor Yellow
- Write-Host " Target IP: $RemoteIP (staaandup = 101, inferno = 105)" -ForegroundColor Yellow
- }
- return $true
- }
- # Main sending loop with better status checking
- $running = $true
- $lastJobCheck = Get-Date
- try {
- while ($running) {
- # Check listener status periodically (every 30 seconds)
- if (((Get-Date) - $lastJobCheck).TotalSeconds -gt 30) {
- $job = Get-Job -Name "LANChatListener_$sessionID" -ErrorAction SilentlyContinue
- if (-not $job -or $job.State -ne 'Running') {
- Write-Host "`nWARNING: Listener has stopped unexpectedly!" -ForegroundColor Red
- Write-Host "You can still send messages, but won't receive any." -ForegroundColor Yellow
- Write-Host "Type '/quit' and restart the script to fix this." -ForegroundColor Yellow
- }
- $lastJobCheck = Get-Date
- }
- # Handle Ctrl+C
- if ([Console]::KeyAvailable) {
- $key = [Console]::ReadKey($true)
- if ($key.Modifiers -eq 'Control' -and $key.Key -eq 'C') {
- Write-Host "`nCtrl+C detected. Use '/quit' to exit gracefully." -ForegroundColor Yellow
- continue
- }
- }
- # Get user input
- $userInput = Read-Host
- # Send message and check if we should continue
- $running = Send-Message -Message $userInput
- }
- } finally {
- # Cleanup
- Write-Host "`nShutting down chat..." -ForegroundColor Yellow
- # Stop listener job
- $jobs = Get-Job -Name "LANChatListener_*" -ErrorAction SilentlyContinue
- foreach ($job in $jobs) {
- if ($job.State -eq 'Running') {
- $job.StopJob()
- Start-Sleep -Milliseconds 500
- Remove-Job $job -Force -ErrorAction SilentlyContinue
- }
- }
- # Clean up any leftover notify icons
- try {
- $notify = New-Object System.Windows.Forms.NotifyIcon
- $notify.Dispose()
- } catch {}
- Write-Host "Chat ended. Goodbye!" -ForegroundColor Green
- }
Advertisement
Add Comment
Please, Sign In to add comment