' Chat Client by William Yu ' This is the easy part! Once you've connected, voila, instant chat (almost)! ' Brief Overview of QSocket (Client-side) ' ' Connect(ServerName AS STRING, PortNum AS INTEGER) AS INTEGER ' -- Connect to the server (can be a name or IP Number) at the specified ' Port number. Returns a socket file descriptor. ' IsServerReady(SocketNum AS INTEGER) AS INTEGER ' -- Non-blocking function call that determines if the server has sent ' some data to the client. $APPTYPE GUI $TYPECHECK ON CONST DELAY = 500 CONST False = 0 CONST True = NOT False DECLARE SUB SendButtonClick DECLARE SUB ButtonClick DECLARE SUB TimerExpired DIM Socket AS QSocket DIM SockNum AS INTEGER SockNum = 0 CREATE MainForm AS QForm Height = 280 Width = 300 Caption = "Chat Client" Center CREATE Label1 AS QLabel Top = 12 Left = 5 Caption = "Server:" END CREATE CREATE Label2 AS QLabel Top = 39 Left = 5 Caption = "Port:" END CREATE CREATE Edit1 AS QEdit Left = 50 Top = 10 Width = 220 Height = 20 Text = "localhost" END CREATE CREATE Edit2 AS QEdit Left = 50 Top = 37 Width = 220 Height = 20 Text = "5000" END CREATE CREATE Button AS QButton Left = 50 Top = 65 Height = 20 Width = 220 Caption = "Connect" OnClick = ButtonClick END CREATE CREATE ListBox AS QListBox Top = 95 Left = 50 Width = 220 Height = 140 END CREATE CREATE Label3 AS QLabel Top = 98 Caption = "Message" END CREATE CREATE Label4 AS QLabel Top = 242 Left = 6 Caption = "Text:" END CREATE CREATE Edit3 AS QEdit Left = 50 Top = 240 Width = 170 Height = 20 END CREATE CREATE SendButton AS QButton Left = 225 Top = 240 Height = 20 Width = 50 Caption = "Send" OnClick = SendButtonClick END CREATE END CREATE DIM Timer1 AS QTimer Timer1.Interval = DELAY Timer1.OnTimer = TimerExpired SUB TimerExpired Timer1.Enabled = False Timer1.Interval = DELAY IF SockNum <= 0 THEN Timer1.Enabled = True EXIT SUB END IF IF Socket.IsServerReady(SockNum) THEN ListBox.InsertItem 0, Socket.ReadLine(SockNum) IF Socket.Transferred < 0 THEN SockNum = 0 ShowMessage "Server disconnected!" END IF END IF Timer1.Enabled = True END SUB SUB SendButtonClick IF SockNum <= 0 THEN ShowMessage "You must be connected to a server first!" ELSE IF Socket.WriteLine(SockNum, Edit3.Text) = -1 THEN Button.Caption = "Disconnect" ShowMessage "ERROR: Disconnected from Server!" END IF END IF END SUB SUB ButtonClick IF Button.Caption = "Disconnect" THEN Timer1.Enabled = False Button.Caption = "Connect" Socket.Close(SockNum) SockNum = 0 Timer1.Enabled = True EXIT SUB END IF SockNum = Socket.Connect(Edit1.Text, VAL(Edit2.Text)) IF SockNum > 0 THEN Button.Caption = "Disconnect" ListBox.InsertItem 0, Socket.ReadLine(SockNum) ELSE SockNum = 0 ShowMessage "Unable to connect to: "+Edit1.Text+" on port "+Edit2.Text END IF END SUB MainForm.ShowModal