Simple Connect with your website or app. Easily integrated with Node.js, .NET Core, PHP, and Java – Complete documentation provided.
ChatStream – Real-Time Chat System is a modern, full-featured communication solution designed to connect users seamlessly and efficiently. Built with cutting-edge backend technologies and a clean, responsive front-end interface, ChatStream guarantees high performance and scalability for any platform.
We take pride in being the only company offering this unique platform, providing you with everything needed to seamlessly connect service providers with customers.
Experience the power of real-time messaging, video calls, and seamless communication firsthand. Watch the demo video below and discover how ChatStream can transform your platform into a hub of instant connection and engagement.
The Real-Time Chat System offers a comprehensive suite of features designed to enhance communication, improve user engagement, and ensure an intuitive experience. Whether you're a small team or a large organization, this system is customizable and scalable to meet your needs.
The chat system uses the following tables:
CREATE TABLE Users ( UserId INT PRIMARY KEY IDENTITY(1,1), UserName NVARCHAR(100), Email NVARCHAR(100), Icon NVARCHAR(255), Status NVARCHAR(255), CreatedDate DATETIME DEFAULT GETDATE(), IsActive BIT DEFAULT 1, LastLoginDate DATETIME );
CREATE TABLE Chats ( ChatId INT PRIMARY KEY IDENTITY(1,1), SenderId INT, ReceiverId INT, Message NVARCHAR(MAX), Attachment NVARCHAR(1000), Audio NVARCHAR(1000), VideoChatLink NVARCHAR(1000), SentAt DATETIME DEFAULT GETDATE(), IsRead BIT DEFAULT 0, FOREIGN KEY (SenderId) REFERENCES Users(UserId), FOREIGN KEY (ReceiverId) REFERENCES Users(UserId) );
The chat system uses the following tables:
CREATE TABLE Users ( UserId INT PRIMARY KEY AUTO_INCREMENT, UserName VARCHAR(100), Email VARCHAR(100), Icon VARCHAR(255), Status VARCHAR(255), CreatedDate DATETIME DEFAULT CURRENT_TIMESTAMP, IsActive TINYINT(1) DEFAULT 1, LastLoginDate DATETIME );
CREATE TABLE Chats ( ChatId INT PRIMARY KEY AUTO_INCREMENT, SenderId INT, ReceiverId INT, Message TEXT, Attachment VARCHAR(1000), Audio VARCHAR(1000), VideoChatLink VARCHAR(1000), SentAt DATETIME DEFAULT CURRENT_TIMESTAMP, IsRead TINYINT(1) DEFAULT 0, FOREIGN KEY (SenderId) REFERENCES Users(UserId), FOREIGN KEY (ReceiverId) REFERENCES Users(UserId) );
The chat system uses the following tables:
CREATE TABLE Users ( UserId SERIAL PRIMARY KEY, UserName VARCHAR(100), Email VARCHAR(100), Icon VARCHAR(255), Status VARCHAR(255), CreatedDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, IsActive BOOLEAN DEFAULT TRUE, LastLoginDate TIMESTAMP );
CREATE TABLE Chats ( ChatId SERIAL PRIMARY KEY, SenderId INT, ReceiverId INT, Message TEXT, Attachment VARCHAR(1000), Audio VARCHAR(1000), VideoChatLink VARCHAR(1000), SentAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, IsRead BOOLEAN DEFAULT FALSE, FOREIGN KEY (SenderId) REFERENCES Users(UserId), FOREIGN KEY (ReceiverId) REFERENCES Users(UserId) );
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
To integrate the chat system with your application:
To generate a Google Cloud API key for Translation:
[ApiController] [Route("api/[controller]")] public class ChatController : ControllerBase { private readonly ChatDbContext _context; public ChatController(ChatDbContext context) { _context = context; } [HttpGet("users")] public async TaskGetUsers() { var users = await _context.Users.Where(u => u.IsActive).ToListAsync(); return Ok(users); } [HttpGet("chat-users/{userId}")] public async Task GetChatUsers(int userId) { var chatUsers = await _context.Chats .Where(c => c.SenderId == userId || c.ReceiverId == userId) .Select(c => new { UserId = c.SenderId == userId ? c.ReceiverId : c.SenderId, UserName = c.SenderId == userId ? _context.Users.FirstOrDefault(u => u.UserId == c.ReceiverId).UserName : _context.Users.FirstOrDefault(u => u.UserId == c.SenderId).UserName }) .Distinct() .ToListAsync(); return Ok(chatUsers); } #region Login [HttpPost] public async Task Login(string username, string password) { var user = await _context.Users .FirstOrDefaultAsync(u => u.UserName == username); if (user == null || user.Password != password) { return Json(new { success = false, message = "Invalid username or password!" }); } var claims = new List { new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddDays(30) }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return Json(new { success = true }); } #endregion #region Users [HttpGet] public IActionResult GetAllUsers() { var users = _context.Users .Where(u => u.IsActive) .Select(u => new { userid = u.UserId, username = u.UserName, email = u.Email, icon = u.Icon }) .ToList(); return Json(users); } [HttpGet] public IActionResult GetUserByID(int userid) { var users = _context.Users .Where(u => u.IsActive && u.UserId == userid) .Select(u => new { userid = u.UserId, username = u.UserName, email = u.Email, icon = u.Icon }) .FirstOrDefault(); return Json(users); } [HttpGet] public IActionResult GetChatUsers(int userId) { var users = _context.Chats .Where(c => c.SenderId == userId || c.ReceiverId == userId) .GroupBy(c => new { UserId = c.SenderId == userId ? c.ReceiverId : c.SenderId }) .Select(g => new { userid = g.Key.UserId, username = _context.Users .Where(u => u.UserId == g.Key.UserId) .Select(u => u.UserName) .FirstOrDefault(), icon = _context.Users .Where(u => u.UserId == g.Key.UserId) .Select(u => u.Icon) .FirstOrDefault(), lastmessage = g.OrderByDescending(c => c.SentAt) .Select(c => string.IsNullOrEmpty(c.Message) ? "No message" : (c.Message.Length > 30 ? c.Message.Substring(0, 30) + "..." : c.Message)) .FirstOrDefault(), status = _context.Users .Where(u => u.UserId == g.Key.UserId) .Select(u => u.Status) .FirstOrDefault() }) .ToList(); return Json(users); } #endregion #region Chat public IActionResult GetChatMessages(int userId, int otherUserId, int page = 1, int pageSize = 5) { var messages = _context.Chats .Where(c => (c.SenderId == userId && c.ReceiverId == otherUserId) || (c.SenderId == otherUserId && c.ReceiverId == userId)) .OrderByDescending(c => c.SentAt) .Skip((page - 1) * pageSize) .Take(pageSize) .ToList(); var totalMessages = _context.Chats .Count(c => (c.SenderId == userId && c.ReceiverId == otherUserId) || (c.SenderId == otherUserId && c.ReceiverId == userId)); bool hasMoreMessages = totalMessages > page * pageSize; return Json(new { messages, hasMoreMessages }); } [HttpPost] public IActionResult SendMessage(int receiverId, string message, string? attachment) { var senderId = Convert.ToInt32(User.FindFirstValue(ClaimTypes.NameIdentifier)); if (string.IsNullOrEmpty(message) && !string.IsNullOrEmpty(attachment)) { message = "You received an attachment."; } var chat = new Chat { SenderId = senderId, ReceiverId = receiverId, Message = message, }; if (!string.IsNullOrEmpty(attachment)) { chat.Attachment = attachment; } _context.Chats.Add(chat); _context.SaveChanges(); return Ok(); } #endregion }
connect_error) { die("Connection failed: " . $conn->connect_error); } // Get Users function getUsers() { global $conn; $sql = "SELECT user_id, username, email, icon FROM users WHERE is_active = 1"; $result = $conn->query($sql); $users = []; while($row = $result->fetch_assoc()) { $users[] = $row; } echo json_encode($users); } // Get Chat Users function getChatUsers($userId) { global $conn; $sql = "SELECT DISTINCT CASE WHEN sender_id = ? THEN receiver_id ELSE sender_id END AS user_id, CASE WHEN sender_id = ? THEN (SELECT username FROM users WHERE user_id = receiver_id) ELSE (SELECT username FROM users WHERE user_id = sender_id) END AS username FROM chats WHERE sender_id = ? OR receiver_id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("iiii", $userId, $userId, $userId, $userId); $stmt->execute(); $result = $stmt->get_result(); $chatUsers = []; while ($row = $result->fetch_assoc()) { $chatUsers[] = $row; } echo json_encode($chatUsers); } // User Login function login($username, $password) { global $conn; $sql = "SELECT * FROM users WHERE username = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $username); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { $user = $result->fetch_assoc(); if ($user['password'] == $password) { echo json_encode(['success' => true, 'user' => $user]); } else { echo json_encode(['success' => false, 'message' => 'Invalid password']); } } else { echo json_encode(['success' => false, 'message' => 'User not found']); } } // Get Messages function getMessages($userId, $otherUserId, $page = 1, $pageSize = 5) { global $conn; $offset = ($page - 1) * $pageSize; $sql = "SELECT * FROM chats WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?) ORDER BY sent_at DESC LIMIT ?, ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("iiiiii", $userId, $otherUserId, $otherUserId, $userId, $offset, $pageSize); $stmt->execute(); $result = $stmt->get_result(); $messages = []; while ($row = $result->fetch_assoc()) { $messages[] = $row; } echo json_encode($messages); } // Send Message function sendMessage($senderId, $receiverId, $message, $attachment = null) { global $conn; $sql = "INSERT INTO chats (sender_id, receiver_id, message, attachment) VALUES (?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("iiss", $senderId, $receiverId, $message, $attachment); if ($stmt->execute()) { echo json_encode(['success' => true]); } else { echo json_encode(['success' => false, 'message' => 'Message sending failed']); } } // Example Usage // You would call these functions in your routing system or based on your HTTP requests if ($_SERVER['REQUEST_METHOD'] === 'GET') { if (isset($_GET['action'])) { switch ($_GET['action']) { case 'getUsers': getUsers(); break; case 'getChatUsers': $userId = $_GET['userId']; getChatUsers($userId); break; case 'getMessages': $userId = $_GET['userId']; $otherUserId = $_GET['otherUserId']; $page = isset($_GET['page']) ? $_GET['page'] : 1; $pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 5; getMessages($userId, $otherUserId, $page, $pageSize); break; } } } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['action'])) { switch ($_POST['action']) { case 'login': $username = $_POST['username']; $password = $_POST['password']; login($username, $password); break; case 'sendMessage': $senderId = $_POST['senderId']; $receiverId = $_POST['receiverId']; $message = $_POST['message']; $attachment = isset($_POST['attachment']) ? $_POST['attachment'] : null; sendMessage($senderId, $receiverId, $message, $attachment); break; } } } $conn->close(); ?>
const express = require('express'); const mysql = require('mysql2'); const bodyParser = require('body-parser'); // Set up Express const app = express(); const port = 3000; // Middleware to parse JSON requests app.use(bodyParser.json()); // MySQL database connection const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'chatdb' }); db.connect((err) => { if (err) { console.error('Database connection failed: ' + err.stack); return; } console.log('Connected to the database'); }); // Get all active users app.get('/getUsers', (req, res) => { db.query('SELECT user_id, username, email, icon FROM users WHERE is_active = 1', (err, results) => { if (err) { return res.status(500).send({ error: 'Database error' }); } res.json(results); }); }); // Get chat users for a specific user app.get('/getChatUsers/:userId', (req, res) => { const userId = req.params.userId; const query = ` SELECT DISTINCT CASE WHEN sender_id = ? THEN receiver_id ELSE sender_id END AS user_id, CASE WHEN sender_id = ? THEN (SELECT username FROM users WHERE user_id = receiver_id) ELSE (SELECT username FROM users WHERE user_id = sender_id) END AS username FROM chats WHERE sender_id = ? OR receiver_id = ? `; db.query(query, [userId, userId, userId, userId], (err, results) => { if (err) { return res.status(500).send({ error: 'Database error' }); } res.json(results); }); }); // User login app.post('/login', (req, res) => { const { username, password } = req.body; const query = 'SELECT * FROM users WHERE username = ?'; db.query(query, [username], (err, results) => { if (err) { return res.status(500).send({ error: 'Database error' }); } if (results.length > 0) { const user = results[0]; if (user.password === password) { return res.json({ success: true, user }); } else { return res.status(401).json({ success: false, message: 'Invalid password' }); } } else { return res.status(404).json({ success: false, message: 'User not found' }); } }); }); // Get messages between two users app.get('/getMessages/:userId/:otherUserId', (req, res) => { const userId = req.params.userId; const otherUserId = req.params.otherUserId; const page = req.query.page || 1; const pageSize = req.query.pageSize || 5; const offset = (page - 1) * pageSize; const query = ` SELECT * FROM chats WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?) ORDER BY sent_at DESC LIMIT ?, ? `; db.query(query, [userId, otherUserId, otherUserId, userId, offset, pageSize], (err, results) => { if (err) { return res.status(500).send({ error: 'Database error' }); } res.json(results); }); }); // Send a message app.post('/sendMessage', (req, res) => { const { senderId, receiverId, message, attachment } = req.body; const query = 'INSERT INTO chats (sender_id, receiver_id, message, attachment) VALUES (?, ?, ?, ?)'; db.query(query, [senderId, receiverId, message, attachment], (err, results) => { if (err) { return res.status(500).send({ error: 'Message sending failed' }); } res.json({ success: true }); }); }); // Start the server app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; SpringBootApplication RestController RequestMapping("/api") public class ChatApplication { Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) { SpringApplication.run(ChatApplication.class, args); } // Get all active users GetMapping("/getUsers") public ListgetUsers() { String sql = "SELECT user_id, username, email, icon FROM users WHERE is_active = 1"; return jdbcTemplate.query(sql, (rs, rowNum) -> new User(rs.getInt("user_id"), rs.getString("username"), rs.getString("email"), rs.getString("icon"))); } // Get chat users for a specific user GetMapping("/getChatUsers/{userId}") public List getChatUsers(PathVariable int userId) { String sql = "SELECT DISTINCT " + "CASE " + " WHEN sender_id = ? THEN receiver_id " + " ELSE sender_id " + "END AS user_id, " + "CASE " + " WHEN sender_id = ? THEN (SELECT username FROM users WHERE user_id = receiver_id) " + " ELSE (SELECT username FROM users WHERE user_id = sender_id) " + "END AS username " + "FROM chats WHERE sender_id = ? OR receiver_id = ?"; return jdbcTemplate.query(sql, new Object[]{userId, userId, userId, userId}, (rs, rowNum) -> new User(rs.getInt("user_id"), rs.getString("username"))); } // User login PostMapping("/login") public Response login(RequestBody LoginRequest loginRequest) { String sql = "SELECT * FROM users WHERE username = ?"; List users = jdbcTemplate.query(sql, new Object[]{loginRequest.getUsername()}, (rs, rowNum) -> new User(rs.getInt("user_id"), rs.getString("username"), rs.getString("password"))); if (users.isEmpty()) { return new Response(false, "User not found"); } User user = users.get(0); if (user.getPassword().equals(loginRequest.getPassword())) { return new Response(true, user); } else { return new Response(false, "Invalid password"); } } // Get messages between two users GetMapping("/getMessages/{userId}/{otherUserId}") public List getMessages(PathVariable int userId, PathVariable int otherUserId, RequestParam(value = "page", defaultValue = "1") int page, RequestParam(value = "pageSize", defaultValue = "5") int pageSize) { String sql = "SELECT * FROM chats " + "WHERE (sender_id = ? AND receiver_id = ?) " + "OR (sender_id = ? AND receiver_id = ?) " + "ORDER BY sent_at DESC LIMIT ?, ?"; return jdbcTemplate.query(sql, new Object[]{userId, otherUserId, otherUserId, userId, (page - 1) * pageSize, pageSize}, (rs, rowNum) -> new Message(rs.getInt("sender_id"), rs.getInt("receiver_id"), rs.getString("message"), rs.getTimestamp("sent_at"))); } // Send a message PostMapping("/sendMessage") public Response sendMessage(RequestBody MessageRequest messageRequest) { String sql = "INSERT INTO chats (sender_id, receiver_id, message, attachment) VALUES (?, ?, ?, ?)"; int result = jdbcTemplate.update(sql, messageRequest.getSenderId(), messageRequest.getReceiverId(), messageRequest.getMessage(), messageRequest.getAttachment()); if (result > 0) { return new Response(true, "Message sent successfully"); } else { return new Response(false, "Message sending failed"); } } // DTOs and Response classes static class User { private int userId; private String username; private String email; private String icon; // Constructors, getters, and setters } static class Message { private int senderId; private int receiverId; private String message; private java.sql.Timestamp sentAt; // Constructors, getters, and setters } static class LoginRequest { private String username; private String password; // Constructors, getters, and setters } static class MessageRequest { private int senderId; private int receiverId; private String message; private String attachment; // Constructors, getters, and setters } static class Response { private boolean success; private String message; private Object data; public Response(boolean success, Object data) { this.success = success; this.data = data; } public Response(boolean success, String message) { this.success = success; this.message = message; } // Constructors, getters, and setters } }
Enhanced chat system with real-time updates and interactive features.
Initial release with real-time chat and video calling functionality.
Future versions will continue to enhance the system with additional features such as:
Your website is a tireless employee, working around the clock, 24 hours a day, 7 days a week, without rest or break. It is the face of your business, representing you to the world, and it needs to be the best it can be. That's why you can trust the expert team at AM-Technology to create the ultimate employee for your business - a website that works for you, day and night.
Contact us