Ejemplo n.º 1
0
void __fastcall TfrmMain::tcpServerExecute(TIdPeerThread *AThread)
{
  TSimpleClient *Client;
  AnsiString Com;     // System command
  AnsiString Msg;

//Get the text sent from the client
try
{
  Msg    = AThread->Connection->ReadLn("",5000);
}
catch (...)
{

}
  // Get the clients package info
if (Msg.Length()==0)return;
  Client = (TSimpleClient *)(AThread->Data);
// Check to see if the clients name has been assigned yet
  if (Client->Name == "Logging In")
   {
   //  if not, assign the name and announce the client
      Client->Name = Msg;
      UpdateClientList();
      BroadcastMessage("System", Msg + " has just logged in.");
      AThread->Connection->WriteLn(memEntry->Lines->Text);
   }
  else
  // If name is set, then send the message
  if (Msg[1] != '@')
    {
    // Not a system command
      BroadcastMessage(Client->Name, Msg);
    }
  else
    {
    // System command
      Com = UpperCase(Trim(Msg.SubString(2, Msg.Pos(":") -2)));
      Msg = UpperCase(Trim(Msg.SubString(Msg.Pos(":") +1, Msg.Length())));
      if (Com == "CLIENTS")
     AThread->Connection->WriteLn( AnsiString("@") + AnsiString("clients:") +
                 lbClients->Items->CommaText);

     if (Com == "KILL")
        KillClient(Msg);
    }


}
Ejemplo n.º 2
0
void CServerSocket::OnClose(int nErrorCode)
{
	CString key,temp;
	key.Format("%s%d",thePeerIp,thePeerPort);
	temp.Format("%d",thePeerPort);
	CMapStringToOb *mapSocket=&(((CCSocketDemoApp*)AfxGetApp())->mapSocket);
	if (mapSocket->GetCount()>0)
	{
		mapSocket->RemoveKey(key);
	}
	UpdateClientList();//solve the exit message.
	theApp.NotifyAll("null",thePeerIp,temp,FALSE);

	Close();
	CAsyncSocket::OnClose(nErrorCode);
}
Ejemplo n.º 3
0
Archivo: xsm.c Proyecto: aosm/X11
static Status
RegisterClientProc(SmsConn smsConn, SmPointer managerData, char *previousId)
{
    ClientRec	*client = (ClientRec *) managerData;
    char 	*id;
    List	*cl;
    int		send_save;

    if (verbose)
    {
	printf (
	"On IceConn fd = %d, received REGISTER CLIENT [Previous Id = %s]\n",
	IceConnectionNumber (client->ice_conn),
	previousId ? previousId : "NULL");
	printf ("\n");
    }

    if (!previousId)
    {
	id = SmsGenerateClientID (smsConn);
	send_save = 1;
    }
    else
    {
	int found_match = 0;
	send_save = 1;

	for (cl = ListFirst (PendingList); cl; cl = ListNext (cl))
	{
	    PendingClient *pendClient = (PendingClient *) cl->thing;

	    if (!strcmp (pendClient->clientId, previousId))
	    {
		SetInitialProperties (client, pendClient->props);
		XtFree (pendClient->clientId);
		XtFree (pendClient->clientHostname);
		XtFree ((char *) pendClient);
		ListFreeOne (cl);
		found_match = 1;
		send_save = 0;
		break;
	    }
	}

	if (!found_match)
	{
	    for (cl = ListFirst (RestartAnywayList); cl; cl = ListNext (cl))
	    {
		ClientRec *rClient = (ClientRec *) cl->thing;

		if (!strcmp (rClient->clientId, previousId))
		{
		    SetInitialProperties (client, rClient->props);
		    FreeClient (rClient, False /* don't free props */);
		    ListFreeOne (cl);
		    found_match = 1;
		    send_save = 0;
		    break;
		}
	    }
	}

	if (!found_match)
	{
	    for (cl = ListFirst (RestartImmedList); cl; cl = ListNext (cl))
	    {
		ClientRec *rClient = (ClientRec *) cl->thing;

		if (!strcmp (rClient->clientId, previousId))
		{
		    SetInitialProperties (client, rClient->props);
		    FreeClient (rClient, False /* don't free props */);
		    ListFreeOne (cl);
		    found_match = 1;
		    send_save = 0;
		    break;
		}
	    }
	}

	if (!found_match)
	{
	    /*
	     * previous-id was bogus: return bad status and the client
	     * should re-register with a NULL previous-id
	     */

	    free (previousId);
	    return (0);
	}
	else
	{
	    id = previousId;
	}
    }

    SmsRegisterClientReply (smsConn, id);

    if (verbose)
    {
	printf (
	"On IceConn fd = %d, sent REGISTER CLIENT REPLY [Client Id = %s]\n",
	IceConnectionNumber (client->ice_conn), id);
	printf ("\n");
    }

    client->clientId = id;
    client->clientHostname = SmsClientHostName (smsConn);
    client->restarted = (previousId != NULL);

    if (send_save)
    {
	SmsSaveYourself (smsConn, SmSaveLocal,
	    False, SmInteractStyleNone, False);

	ListAddLast (InitialSaveList, (char *) client);
    }
    else if (client_info_visible)
    {
	/* We already have all required client info */

	UpdateClientList ();
	XawListHighlight (clientListWidget, current_client_selected);
    }

    return (1);
}
Ejemplo n.º 4
0
Archivo: xsm.c Proyecto: aosm/X11
void
CloseDownClient(ClientRec *client)
{
    int index_deleted = 0;

    if (verbose) {
	printf ("ICE Connection closed, IceConn fd = %d\n",
		IceConnectionNumber (client->ice_conn));
	printf ("\n");
    }

    SmsCleanUp (client->smsConn);
    IceSetShutdownNegotiation (client->ice_conn, False);
    IceCloseConnection (client->ice_conn);

    client->ice_conn = NULL;
    client->smsConn = NULL;

    if (!shutdownInProgress && client_info_visible)
    {
	for (index_deleted = 0;
	    index_deleted < numClientListNames; index_deleted++)
	{
	    if (clientListRecs[index_deleted] == client)
		break;
	}
    }

    ListSearchAndFreeOne (RunningList, (char *) client);

    if (saveInProgress)
    {
	Status delStatus = ListSearchAndFreeOne (
	    WaitForSaveDoneList, (char *) client);

	if (delStatus)
	{
	    ListAddLast (FailedSaveList, (char *) client);
	    client->freeAfterBadSavePopup = True;
	}

	ListSearchAndFreeOne (WaitForInteractList, (char *) client);
	ListSearchAndFreeOne (WaitForPhase2List, (char *) client);

	if (delStatus && ListCount (WaitForSaveDoneList) == 0)
	{
	    if (ListCount (FailedSaveList) > 0 && !checkpoint_from_signal)
		PopupBadSave ();
	    else
		FinishUpSave ();
	}
	else if (ListCount (WaitForInteractList) > 0 &&
	    OkToEnterInteractPhase ())
	{
	    LetClientInteract (ListFirst (WaitForInteractList));
	}
	else if (!phase2InProgress &&
	    ListCount (WaitForPhase2List) > 0 && OkToEnterPhase2 ())
	{
	    StartPhase2 ();
	}
    }

    if (client->restartHint == SmRestartImmediately && !shutdownInProgress)
    {
	Clone (client, True /* use saved state */);

	ListAddLast (RestartImmedList, (char *) client);
    }
    else if (client->restartHint == SmRestartAnyway)
    {
	ListAddLast (RestartAnywayList, (char *) client);
    }
    else if (!client->freeAfterBadSavePopup)
    {
	FreeClient (client, True /* free props */);
    }

    if (shutdownInProgress)
    {
	if (ListCount (RunningList) == 0)
	    EndSession (0);
    }
    else if (client_info_visible)
    {
	UpdateClientList ();

	if (current_client_selected == index_deleted)
	{
	    if (current_client_selected == numClientListNames)
		current_client_selected--;

	    if (current_client_selected >= 0)
	    {
		XawListHighlight (clientListWidget, current_client_selected);
		ShowHint (clientListRecs[current_client_selected]);
		if (client_prop_visible)
		{
		    DisplayProps (clientListRecs[current_client_selected]);
		}
	    }
	}
	else
	{
	    if (index_deleted < current_client_selected)
		current_client_selected--;
	    XawListHighlight (clientListWidget, current_client_selected);
	}
    }
}
Ejemplo n.º 5
0
/////////////////////////////////////////////////////////////////////////////
// CClientSocket member functions
void CClientSocket::OnReceive(int nErrorCode)
{
	CString ip;UINT port;
	CString buf,text;
	CString _fileName;
	byte* mybuf=new byte[PACKAGESIZE];
	//Receive(buf.GetBuffer(2056),2056);
	int total=Receive(mybuf,PACKAGESIZE);
	buf.Format("%s",mybuf);
	GetPeerName(ip,port);
	int isTxtMsg=0;

	if (buf.Find("<?Request FILETRANSFER?>")>-1)
	{
		closed=0;
		int pos=buf.Find(":");
		int posEnd=buf.Find(":",pos+1);
		//_fileName=buf.Right(buf.GetLength()-pos-1);
		_fileName=buf.Mid(pos+1,posEnd-pos-1);
		fileLen=buf.Mid(posEnd+1,buf.GetLength()-posEnd-1);
		fileLength=atol(fileLen.GetBuffer(0));
		fileName=_fileName;
		CString request;
		request.Format("来自%s的用户向你发送文件%s,是否接收?",ip,_fileName);
		int ret=MessageBox(pcwnd->GetSafeHwnd(),request,"文件发送请求",MB_ICONQUESTION|MB_YESNO);
		if (ret==IDYES)
		{
			CString suffix=fileName.Right(fileName.GetLength()-fileName.ReverseFind('.')-1);
			CFileDialog dlg(FALSE,suffix,fileName);
			dlg.m_ofn.lpstrTitle="请选择保存位置";
			dlg.m_ofn.lpstrFilter="所有文件类型(*.*)\0*.*\0\0";
			if (IDOK==dlg.DoModal())
			{
				filePath=dlg.GetPathName();
				fileName=dlg.GetFileName();
				destFile.Open(filePath,CFile::modeWrite|CFile::modeNoTruncate|CFile::modeCreate|CFile::typeBinary,NULL);
				if (!fileTran)
				{
					CSendFileDlg *sfDlg=new CSendFileDlg(SOCKETTYPECLIENT,this);
					sfDlg->Create(IDD_SENDFILE_DIALOG,CWnd::FromHandle(::GetDesktopWindow()));
					fileTran=sfDlg;
					fileTran->ShowWindow(SW_SHOW);
 				}
				fileTran->SetDlgItemText(IDC_STATIC_SRCA,thePeerIp);
				fileTran->SetDlgItemText(IDC_STATIC_DESA,localIp);
				fileTran->SetDlgItemText(IDC_STATIC_FINFO,fileName+"\n大小: "+fileLen+" 字节");
				CProgressCtrl *proSF=(CProgressCtrl*)fileTran->GetDlgItem(IDC_PROGRESS_TRANFILE);
				proSF->SetRange32(0,fileLength);
				proSF->SetPos(0);
				Send("<?Response FILETRANSFER?>:ACCEPT",256);
			}
			else
				Send("<?Response FILETRANSFER?>:REFUSE",256);
		}
		else
		{
			Send("<?Response FILETRANSFER?>:REFUSE",256);
		}
	}
	else if (buf.Find("<?PlainMsg?>")>-1)
	{
		tag=1;isTxtMsg=1;
	}
	else if (buf.Find("<?FileStop?>")>-1)
	{
		if (closed==0)
		{
			destFile.Flush();
			destFile.Close();
			closed=1;
		}
	}
	else if (buf.Find("<?Command update client list?>")>-1)
	{
		int tag=1;
		int pos1,pos2;
		BOOL isAdd=FALSE;
		if (buf.Find("<?Command update client list?>+")>-1)
			isAdd=TRUE;
		if (isAdd)//redraw the client list
		{
			CListCtrl *lc=(CListCtrl*)AfxGetMainWnd()->GetDlgItem(IDC_LIST_CLIENT);
			lc->DeleteAllItems();
		}

		buf.Replace('#','+');
		CString sztemp;
		while(tag)
		{
			pos1=buf.Find("+");
			pos2=buf.Find("+",pos1+1);
			if (pos1==-1)
				break;
			if(pos2==-1)
			{
				pos2=buf.GetLength();
				tag=0;
			}
			sztemp=buf.Mid(pos1+1,pos2-pos1-1);
			buf=buf.Right(buf.GetLength()-pos2);
			UpdateClientList(CString("<?Command update client list?>")+sztemp,isAdd);
		}
	}
	else if (buf.Find("<?Command Kick?>")>-1)
	{
		AfxMessageBox("你已被服务器踢出,\n点击 确定 结束程序。",MB_ICONINFORMATION);
		CCSocketDemoDlg *ccd=(CCSocketDemoDlg*)AfxGetMainWnd();
		NOTIFYICONDATA *_nd=&(ccd->nd);
		Shell_NotifyIcon(NIM_DELETE, _nd);
		::PostQuitMessage(0);
	}
	else
	{
		destFile.SeekToEnd();
		destFile.Write(mybuf,total);
		//destFile.Flush();
		CProgressCtrl *proSF=(CProgressCtrl*)fileTran->GetDlgItem(IDC_PROGRESS_TRANFILE);
		proSF->SetPos(proSF->GetPos()+total);
		CString status;
		status.Format("已接收%u 字节中的%d 字节",fileLength,proSF->GetPos());
		fileTran->SetDlgItemText(IDC_STATIC_STATUS,status);
		if (fileLength==proSF->GetPos() &&closed==0)
		{
			destFile.Flush();
			destFile.Close();
			closed=1;
		}
		Send("<?FileContinue?>",256);
	}


	if (isTxtMsg==0)
	{
		delete[] mybuf;
		buf.Empty();
		return;
	}
	if (AfxGetMainWnd()->IsWindowVisible()==FALSE)
		AfxGetMainWnd()->SetTimer(2,800,NULL);//flash icon
	else
		AfxGetMainWnd()->SetTimer(1,800,NULL);//flash window
	PlaySound(MAKEINTRESOURCE(IDR_WAVE_MSG),AfxGetInstanceHandle(),SND_RESOURCE|SND_ASYNC|SND_NOWAIT);

	CRichEditCtrl *m_RichEdit1;
	pcwnd=AfxGetApp()->GetMainWnd();
	m_RichEdit1=(CRichEditCtrl*)pcwnd->GetDlgItem(IDC_RICHEDIT_CONTENT);
	SOCKADDR_IN addrFrom;
	int len=sizeof(SOCKADDR);
	CString msg;
	HOSTENT *pHost;
	DWORD lineCount=m_RichEdit1->GetLineCount();

	CHARFORMAT cf;
	ZeroMemory(&cf, sizeof(CHARFORMAT));
	cf.cbSize = sizeof(CHARFORMAT);
	cf.dwMask = CFM_BOLD | CFM_COLOR | CFM_FACE |
		CFM_ITALIC | CFM_SIZE | CFM_UNDERLINE;
	cf.dwEffects = 0;
	cf.yHeight = 15*15;//文字高度
	cf.crTextColor = RGB(255, 0, 0); //文字颜色
	strcpy(cf.szFaceName ,_T("宋体"));//设置字体
	m_RichEdit1->SetDefaultCharFormat(cf);
	m_RichEdit1->SetBackgroundColor(FALSE,RGB(255,255,255));
	
	//ReceiveFrom(buf.GetBuffer(2056),2056,(SOCKADDR*)&addrFrom,&len);

	DWORD peerIP=inet_addr(ip.GetBuffer(0));  
	pHost=gethostbyaddr((LPSTR)&peerIP,4,AF_INET); 

	buf=buf.Right(buf.GetLength()-13);

	CTime time=CTime::GetCurrentTime();
	CString currentTime;
	currentTime.Format("          %02d:%02d:%02d",time.GetHour(),time.GetMinute(),time.GetSecond());

	host.Format("[系统消息] %s%s",pHost->h_name,currentTime);
	msg.Format("\r\n  %s\r\n",buf);

	cf.yHeight = 13*13;//文字高度
	cf.crTextColor = RGB(0,110,254); //文字颜色
	strcpy(cf.szFaceName ,_T("微软雅黑"));//设置字体
	m_RichEdit1->SetSel(m_RichEdit1->GetTextLength(),m_RichEdit1->GetTextLength());
	m_RichEdit1->ReplaceSel(host);
	m_RichEdit1->SetSel(m_RichEdit1->GetTextLength()-host.GetLength(),m_RichEdit1->GetTextLength());
	m_RichEdit1->SetSelectionCharFormat(cf);
	
	m_RichEdit1->SetSel(-1,-1);
	m_RichEdit1->ReplaceSel(msg);
	cf.yHeight = 14*14;//文字高度
	cf.crTextColor = RGB(204,0,204); //文字颜色
	strcpy(cf.szFaceName ,_T("微软雅黑"));//设置字体
	m_RichEdit1->SetSel(m_RichEdit1->GetTextLength()-msg.GetLength(),m_RichEdit1->GetTextLength());
	m_RichEdit1->SetSelectionCharFormat(cf);
	m_RichEdit1->LineScroll(m_RichEdit1->GetLineCount()-lineCount);
	m_RichEdit1->SetSel(0,0);

	delete[] mybuf;
	buf.Empty();
	CAsyncSocket::OnReceive(nErrorCode);
}
Ejemplo n.º 6
0
void __fastcall TfrmMain::btnClientsClick(TObject *Sender)
{
  UpdateClientList();
}