
Originariamente inviata da
cavicchiandrea
Impossibile rispondere senza conoscere chatusb ai tentativi e prove
Bè hai ragione effettivamente....allora partiamo dal codice lato server che penso ci interessa poco questo è il tutto (parliamo di Signalr libreria open source per applicazioni in tempo reale):
codice:
Imports Microsoft.AspNet.SignalR
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports WebApplication1.SignalRChat.Common
Namespace SignalRChat
Public Class ChatHub
Inherits Hub
#Region "Data Members"
Shared ConnectedUsers As New List(Of UserDetail)()
Shared CurrentMessage As New List(Of MessageDetail)()
#End Region
#Region "Methods"
Public Sub Connect(userName As String)
Dim id = Context.ConnectionId
If ConnectedUsers.Where(Function(x) x.ConnectionId = id).Count = 0 Then
ConnectedUsers.Add(New UserDetail() With { _
.ConnectionId = id, _
.UserName = userName _
})
' send to caller
Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage)
' send to all except caller client
Clients.AllExcept(id).onNewUserConnected(id, userName)
End If
End Sub
Public Sub SendMessageToAll(userName As String, message As String)
' store last 100 messages in cache
AddMessageinCache(userName, message)
' Broad cast message
Clients.All.messageReceived(userName, message)
End Sub
Public Sub SendPrivateMessage(toUserId As String, message As String)
Dim fromUserId As String = Context.ConnectionId
Dim toUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = toUserId)
Dim fromUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = fromUserId)
If toUser IsNot Nothing AndAlso fromUser IsNot Nothing Then
' send to
Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message)
' send to caller user
Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message)
End If
End Sub
Public Overrides Function OnDisconnected(stopCalled As Boolean) As Threading.Tasks.Task
Dim item = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = Context.ConnectionId)
If item IsNot Nothing Then
ConnectedUsers.Remove(item)
Dim id = Context.ConnectionId
Clients.All.onUserDisconnected(id, item.UserName)
End If
Return MyBase.OnDisconnected(stopCalled)
End Function
#End Region
#Region "private Messages"
Private Sub AddMessageinCache(userName As String, message As String)
CurrentMessage.Add(New MessageDetail() With { _
.UserName = userName, _
.Message = message _
})
If CurrentMessage.Count > 100 Then
CurrentMessage.RemoveAt(0)
End If
End Sub
#End Region
End Class
End Namespace
Ora il javascript e jquery:
Codice posto sulla pagina home.aspx:
codice:
<script type="text/javascript">
function Loggin7() {
var value = document.getElementById('<%=LoginName1.ClientID%>').innerHTML;
var name = $("#txtNickName").val(value);
}
</script>
<script type="text/javascript">
var stoptimer;
function my_code() {
stoptimer = setTimeout("my_code()", 2000);
document.getElementById("btnStartChat").click();
clearTimeout(stoptimer);
}
window.onload = my_code();
</script>
Infine il codice della pagina master:
codice:
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").show();
$("#divLogin").hide();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var image = ("<img src='Images/tn_ball.gif' />");
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(image + ' ' + ' ' + name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" Disconnesso.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
var data = new Date();
var mese = data.getMonth() + 1;
if (mese < 10) {
mese = '0' + mese;
} else {
mese = mese + '';
}
var giorno = data.getDate();
var anno = data.getFullYear();
var ora = data.getHours();
if (ora < 10) {
ora = '0' + ora;
} else {
ora = ora + '';
}
var minuti = data.getMinutes();
if (minuti < 10) {
minuti = '0' + minuti;
} else {
minuti = minuti + '';
}
var oggi = giorno + "/" + mese + "/" + anno + " " + ora + ":" + minuti;
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + " " + "" + "(" + oggi + ")" + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
La parte dell'errore è questa funzione quì:
codice:
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var image = ("<img src='Images/tn_ball.gif' />");
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(image + ' ' + ' ' + name);
}
else {
alert("Please enter name");
}
});
Grazie comunque per l'interessamento.
Un saluto.