Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | anurag0290 |
View: | 51 times |
Download: | 2 times |
Notre Dame UniversityFaculty Of Natural And Applied Sciences
Department of computer Science
DEVELOPING ACHAT SERVER
A senior study inComputer Science
By
Waleed Farah
Fall 2000
ii
Abstract
Teleconferencing or Chatting, is a method of using technology to bring people and
ideas “together” despite of the geographical barriers. The technology has been
available for years but the acceptance it was quit recent. Our project is an example of
a chat server. It is made up of 2 applications the client application, which runs on the
user’s Pc and server application, which runs on any Pc on the network. To start
chatting client should get connected to server where they can practice two kinds of
chatting, public one (message is broadcasted to all connected users) and private one
(between any 2 users only) and during the last one security measures were taken.
iii
Acknowledgments
Many People contributed to the success of this project. Although a single
sentence hardly suffices, I would like to thank some of the key people:
Mr. Youssif Simonouglo, Professional Technical Support Sita; Mr. Maroun Attallah,
Director of N.D.U Computer Center, and all N.D.U Computer Center Staff.
For their helpful comments and suggestions, I thank:
Mr. Armen Balian, N.D.U Analyst and Programmer.
Mr. Victor Sawma, N.D.U Analyst and Programmer.
Special thanks to Dr. Marie khair for supervisoring this project all the semester.
Another special thanks go to my teachers, friends, and my family, whose
patience and encouragement were the catalyst of this project.
iv
Dedication
This book is dedicated to you, the reader, for deciding to embark on fascinating
journey of discovery and exploration so that you can implement innovate windows
sockets application.
v
Table of Contents
1. Introduction 11.1. Why Chat Server? 21.2. Why Visual Basic? 21.3. General OverView 3
2. Network Programming 42.1. Network application 52.2. Protocol Stacks 5 2.2.1. TCP 6 2.2.2. IP 62.3. Service Port 72.4. Sockets 7 2.4.1. What is WinSock? 8 2.4.1. How WinSock Works 8 2.4.3. Family Protocols 102.5. Client – Server Application 102.6. Blocking Vs. Non-Blocking 112.7. System Requirement 12
3. Windows Socket With Visual Basic 13 3.1. Properties Of Windows Socket Control 14 3.1.1. Host Name Property 14 3.1.2. Remote Port Property 15 3.1.3. Local Port Property 15 3.1.4. Protocol Property 15 3.1.5. Action Property 16 3.1.6. State Property 16 3.1.7. RecvLen Property 17 3.1.8. Send Data Property 17 3.1.9. Address Family 17 3.1.10. SocketType property 17 3.1.11. BufferSize Property 18 3.1.12. Binary Property 18 3.2. Method of Windows Socket Control 18 3.2.1. Accept Method 18 3.2.2. Close Method 19 3.2.3. Listen Method 19 3.2.4. Connect Method 19 3.3. Events 19 3.3.1. Read Event 20 3.3.2. Disconnect Event 20 3.3.3. Connect Event 20
4. Algorithm Used4.1. Project Structure 21 4.1.1. Control String 22 4.1.2. Client 23 4.1.3. Server 24
vi
4.2. Private Chatting 25
5. Problem Encountered 26 5.1. Multi User 27 5.2. How To Allow Multi User 27 5.3. Private Chatting 30 5.4. Keep Track Of Users 30 5.5. How To Keep Track Of Users 30 5.6. Private Chatting 31 5.6.1. Open Window 31 5.6.2. Keep Track Of Windows 32
6. Encryption 33 6.1. Data Encryption/Decryption 34 6.2. XOR Encryption 35
Conclusion 38References 39
vii
List Of Figures
Figure 4.1.2.1. Client Form 23Figure 4.1.3.1. Server Form 24Figure 4.2.1. Private Form 25Figure 5.2.1 Multi Users 29
List Of Tables
Table 2.4.1. Windows Socket Layer 9Table 3.1.1. Server States 16
viii
CHAPTER 1
INTRODUCTION
In this chapter we are going to deal with the major points behind choosing a chatserver as a senior project and why visual basic is the programming language Ichoose, with a general overview about the project and how it works. So turn thispage quickly and get yourself ready to find how it is working.
1.1. Why Chat Server ?
One year ago I was reading an article about Teleconferencing / chatting, which
as we said it is a method of using technology to bring people and ideas “together”
despite of the geographic barriers. From that time and on I started wondering if I can
participate in that technology and how? The idea of creating a chat server was
initiated and it has two dimensions, one to have an experience in network
programming and the other is to let people conduct meetings with others in different
ix
locations. Such that it crosses time zones, can reach many people, and reduce the
paper flood.
1.2. Why Visual Basic ?
Two main reasons let me choose Visual Basic as the programming language
for this project. The first is that Visual Basic 6 is Microsoft’s latest and greatest
language for Visual programming. Although writing programs can be a tedious chore
at times, Visual Basic reduces the effort required on your part and makes
programming enjoyable. Visual Basic makes many aspects of programming as simple
as dragging graphic objects onto the screen with your mouse.
The second reason which is the main one is that we are going to use a control
called windows socket or WinSock as you will see in the following chapters, and this
control is some how has a low level interface. The only high level languages that
deal with windows sockets is Visual Basic and Visual C++, and since Visual Basic is
more easy to learn in small period of time than Visual C++, it was chosen to be the
programming language.
1.3. General Overview
As a matter of fact there are several varieties of chatting. The simplest
computer chatting is a method of sending, receiving, and storing typed messages with
a network of users. This network could be WAN (Wide Area Network) or LAN(Local
Area Network). Our chatting system will deal only with LAN’s (static IP address) and
it is made up of two applications one runs on the server side (any computer on the
network you choose it to be the server) while the other is delivered and executed on
x
the client PC. Every time the client wants to chat he runs the client application, enter
his user name, host name where the server application is running, and hits the connect
button and start chatting. The system is many-to-many arrangement; every–one is
able to “talk” to anyone else. Messages may be broadcasted to all receivers
(recipients are automatically notified of incoming messages) or sent to special
individuals (private chatting through server) where during this operation all messages
are encrypted at the sender side and decrypted at the recipient to disallow any hackers
to the server from reading these private messages. For this system to be physically
realized you should be familiar with programming and networking. Visual Basic is
our programming language, TCP/IP is our network protocol, and finally “windows
sockets” is our programming interface to have access to network functionality. This
is a first glance at our senior project and the rest of explanations and ideas are eagerly
waiting for you in the next chapters.
xi
CHAPTER 2
NETWORK PROGRAMING
In this chapter, we are going to give some light on the main concepts and ideas we use
to build our project. What we mean by network application, protocols, ports, and how
do they interact with each other. Windows sockets, how it works and how we are
going to use it in our application. All these information will be available for you in
this chapter.
xii
2.1. Network Application
Network application exchange data between physically separated machines.
For this to occur the machines must be connected by a transmission media. There are
many different types of communication links and new ones continue to be developed.
Coaxial cables, phone lines, digital phone lines, fiber optic cable, satellite beam, and
infrared waves are all used as transmission media for exchange data between
computers.
A network includes a group of computers connected by a physical link
allowing data to be exchanged between them. A local are network on LAN is a
network of computers in close physical proximity, usually a single building, but can
be a group of adjacent buildings. Over the last decades LANs have become an
important component of the computer workplace.
2.2. Protocol Stacks
Very Early in the history of computer network development the concept of
separating the problem into multiple levels was adapted. With a multilevel
architecture each layer can handle a different aspect of networking and provide that
functionality to the above layer. TCP/IP is a specific implementation of a multi level
network architecture. In both, the first and second chapter, we are always repeating
the same sentence, which is TCP/IP protocol. It is now the time to dissect this
sentence.
xiii
2.2.1. TCP
TCP (the “Transmission Control Protocol “) has the responsibility for
breaking up the message into datagrams, reassembling them at the other end,
resending anything that gets lost, and putting things back in the right order. It may
seem that TCP is doing all the work. And in small network it is true. With TCP, there
is no maximum message length. When a message is passed to the TCP protocol, if it
is too large to be sent in one peace, the message is broken up into chunks or packets
and sent one at a time to the destination address. The TCP packet contains the
addressing information. The TCP message also contains a packet number and total
number of packets. Because of the nature of the TCP/IP protocol, the packet may
travel different paths and may arrive in a different order than sent. TCP reassemble
the packets in the proper order and requests the retransmission of any missing or
corrupted packets. TCP enables you to create and maintain a connection to a remote
computer. By using the connection, both computers can stream data between each
other.
2.2.2. IP
As the number of computers networked become larger, a system becomes
necessary to give remote computers the capability to recognize other remote
computers; thus the IP addressing method was born. Therefore, simply an IP address
uniquely identifies any computer connected to a network. This address is made up of
32 bits divided into 4 four bytes. But since the number of connected computers is too
large and since it is difficult to remember all their IP addresses, the Domain Name
Service (DNS) was designed. It has the job of transforming the unique computer
xiv
names (host name) into an IP address. Therefor, whenever in our project we run the
client application and enter the host name, this means that we are writing the IP
address of the remote computer we want to connect to indirectly. In general, TCP/IP
is a set of protocols developed to allow cooperating computers to share resources
across the network.
2.3. Service Port
Till now, we have seen that TCP/IP forms the backbone for communication
between computers, but do you know how these computers speak to each other?
The answer is Ports. A port is a special location in the computer’s memory that
exists when two computers are communicating via TCP/IP. Application uses a port
number to communicate and the sending and receiving computers use this same port
to exchange data. To make the job of communication easier, some port numbers have
been standardized, ex, (www Port 80, Ftp Port 20, 21, Etc). Our application uses a
constant named IP-echoport = 7.
2.4. Sockets
The world is defining itself as a largely Intel-processor, windows-based set of
desktops communicating with back end servers of various types. Hardware and
software technology advances are pushing PC’s into the role of every where
communications devices. For software applications to take advantage of increasingly
sophisticated and feature-rich communications technology, they require an
Application Programming Interface (API) which provides a simple and uniform
access to this technology. WinSock has been this interface for TCP/IP on windows
xv
systems for the last 3 years. It is now set to become the definitive applications
interface for all windows-based communication-capable applications.
2.4.1. What is WinSock ?
Windows Socket or “WinSock” as it has become known, is an open
network API standard. It was first designed to create a standard programming
interface for TCP/IP on all versions of Microsoft Windows including Windows 3.x.
The major benefit of WinSock to date have come in 3 areas. First, by providing an
open API standard rather than a closed propriety API, it has helped foster the success
of TCP on Microsoft operating system. Second, application developers have been
able to easily create applications that will run on many different vendors’ TCP/IP
network stack. Third, it has made it much easier for end users to select both
applications and network stacks – they need only look for WinSock compatibility.
There are now hundreds of WinSock-capable applications and an ever-increasing
number of users mandating and relying on this open standard for the connectivity
delivered by their TCP/IP applications.
2.4.2. How WinSock Works
The previous sections described what information a program needs to
communicate over a TCP/IP network. The next step is for a program to create what
is called a socket; a communication end-point that can be linked to a telephone.
However, creating a socket by itself doesn’t let you exchange information (having a
telephone doesn’t mean that you can talk by simply taking it off the hook). You need
xvi
to establish a connection with the other program. Table 2.4.1. shows how winsock
works
Table 2.4.1 the windows socket layer
Wireless stackTCP/IP Stack
Wireless
Service provider Interface
(SPI)
Name Space
SPI
TCP/IP
Protocol Specific
Annex
TCP/IP
SPI
Winsock 2 DLLS
Application Layer
The winsock DLL is a layer between an application and the TCP/IP stack. The
application tells the Winsock DLL what to do. These instructions then go to the
TCP/IP stack, and the TCP/IP stack passes them along to the network. To do this,
you need a socket address of the application that you want to connect to. This
address consists of 3 parts: protocol family, Internet protocol, and the service port
number. We have already covered the service port and protocol, but what is protocol
family?
xvii
2.4.3. Family Protocol
It is a number used to logically designate the group that a given protocol
belongs to. Since the socket is general enough to be used with any protocols, the
protocol family tells the underling network software which protocol is being used by
the socket. In our project it is given the value AF_INET, which s a global constant
with the integer value of 2.
2.5. Client-Server Application
When the program wishes to use TCP to exchange data, one of the programs
should take the role of a client while the other must take the role of a server. The
client application initiates what is called active open. It creates a socket and actively
attempts to connect to server program. On the other hand, the server application
creates a socket and passively listens for incoming connections from client,
performing what is called passive open. When the client wants to connect a server, it
sends a connection request. The server is notified that some process is trying to
connect with it. By accepting the connection, the server completes what is called a
virtual circuit, a logical communication pathway between the two programs.
To review, there are five significant steps that a program that uses TCP must take to
establish and complete a connection.
xviii
• The server side would follow these steps:
1. Create a socket
2. Listen for incoming connections from clients
3. Accept the client connection
4. Send and receive information
5. Close the socket when finished, terminating the conversation
• In case of the client, these steps are followed:
1. Create a socket
2. Specify the address and service port of the server program
3. Establish the connection with the server
4. Send and receive information
5. Close the socket when finished, terminating the conversation
2.6. Blocking vs. Non-blocking Mode
A socket can operate in blocking or non-blocking mode. This mode is
associated with the socket and affects the operation of all relevant commands on that
socket. The socket commands affected by the blocking mode are: Accept ( ),
Connect ( ), Disconnect ( ), Read ( ), Write ( ).
In general, in blocking mode, commands wait to return until the required
network activity completes, while in the non-blocking mode, commands fail if the
required network activity has not completed when the command is issued. In non-
blocking mode, issuing a command can be used as a method of polling for the
xix
associated network event completion. It is highly recommended that in WinSock
application to use the non-blocking mode as my application does.
2.7. System Requirements
The SocketWrench control requires Microsoft Windows 3.1 or later, Visual
Basic 2.0 or later and networking software that supports the Windows Sockets 1.1
specification. For 16-bit platforms, the Visual Basic or ActiveX control should be
installed in the system directory. For 32-bit platforms, the ActiveX control should be
placed in the system directory under Windows 95, or the system32 directory under
Windows NT.
Windows 3.1 does not come with TCP/IP software as part of the operating
system, so you will need a third-party product for that platform. One of the most
popular TCP/IP stacks for this platform is written by Trumpet Software International,
and can be used over local and dial-up networks. Windows for Workgroups 3.11 does
not include TCP/IP software, but Microsoft does offer one for free. However, it does
not support dial-up networks, so if that is a requirement, you will still need a third-
part product.
Windows 95 and Windows NT both have TCP/IP software included with the
operating system. Both local and dial-up networks are supported, with dial-up
networking installed as part of the Windows Remote Access Services subsystem. If
you are using Windows 95, it is recommended that you obtain the Dial-Up
networking 2.1 update that includes a number of enhancements to the product. You
xx
can obtain further information about this update by searching the KnowledgeBase on
the Microsoft website.
xxi
CHAPTER 3
WINDOWS SOCKETS WITH VISUAL BASIC
With the acceptance of the TCP/IP as a standard platform-independent network
protocol, and the explosive growth of the internet, the Windows Socket API
(Application Program Interface) has emerged as the standard for network
programming in the Window’s environment. There are two general approaches that
you can follow when creating a program that uses Windows Sockets. The first is to
code directly against the API. The second-which we use in our project-is to use a
component, which provides a higher level interface to the library by setting properties
and responding to events, which we will describe later in the next chapters. So this
chapter has the responsibility of describing this control and how we can make use of it
in our project. Therefore, psyche yourself up to get motivated to explore the beauty
of Windows Socket Control.
xxii
3.1. Properties of Windows Socket Control
Winsock/socket wrench enables you to create clients and servers using the
same control. These dual functioning enables you to specify through property setting
the type of application you will be building. The socket control uses a number of the
same properties, whether you are creating a client or a server, thereby all but
eliminating the learning curve needed to create applications. The next couple of
sections describe some of the properties we used and available to the socket control
and how they can be called in an application.
3.1.1. Host Name Property
The Host Name Property returns or sets the remote host. Remote host
can be both read from and written to and is available both at design time and run
time. The value returned is a string and can be specified either as IP address such as
(204.246.66.6) or as DNS name (www.microsoft.com). The following is an example
of the syntax to read the property:
RetVa1 = winsock.Hostname
To set the property, you use: winsock.Hostname = “127.0.0.2”
Sitting this property at run time enables the user to select the remote host when the
application starts or based on some criteria.
xxiii
3.1.2. Remote Port Property
The Remote Port Property returns or sets the remote port number. This
property can be both read from and written to and is available both at design time
and run time. The value returned is a long integer. An example of the syntax to read
property is:
RetVar = winsock.remoteport
To set the property, use the following:
Winsock.remoteport = 7
This property can be used to select the application that is to be contacted at the
remote host.
3.1.3. Local Port Property
The Local Port Property returns or sets the local port number. Local Port
can be both read from and written to and is available both at design time and run
time. The value returned is a long integer. The following is an example of syntax to
read the property:
RetVar = winsock.localportTo set the property, you use the following:
Winsock.localport = 7
3.1.4. Protocol Property
The Protocol Property returns or sets the protocol of either UDP or TCP.
This property can be both read from and written to and is available both at design
time and run time. The value returned is 0 (or the constant SckTCP Protocol) or 1
(SckUDPProtocol). Example:
xxiv
RetVar = winsock.ProtocolTo set the property, you use:
Winsock.localport = SckTCPProtocol
3.1.5. Action Property
Setting this property causes the socket to take some action, such as creating
a socket connecting to a remote system or closing a connection. Example:
Winsock.Action = action
3.1.6. State Property
The State Property returns the state of the control as expressed by
enumerated list. This property is read-only and is unavailable at design time. The
state property is set by using various methods and events. The syntax to read the
property: RetVar = winsock.state
Table 3.1.1. shows the setting for the state property:
Table 3.1.1. server states
Constant Value DescriptionSckClosed 0 DefaultSckOpen 1 Open
SckListening 2 ListeningSckConnection Pending 3 Connection Pending
SckResolving Host 4 Resolving HostSckHost Resolved 5 Host Resolved
SckConnecting 6 ConnectingSckConnected 7 Connected
SckClosing 8 ClosingSckError 9 Error
xxv
3.1.7. RecvLen Property
Sets the maximum number of bytes to read, or return the number of bytes
read. Example:
Winsock.Recvlen = [[ number of characters to be sent ]]
3.1.8. Send Data Property
Writes data to the remote server. Example:
Winsock.Senddata = [[ data to be sent ]]
3.1.9. AddressFamily property
This property is part of the socket address, and should always be set
to a value of AF_INET, which is global constant with the integer
value of 2.
3.1.10 SocketType property
This property specifies the type of socket that is to be created. It
may be either of type SOCK_STREAM or SOCK_DGRAM. The stream-
based socket uses the TCP protocol, and data is read and written on the
socket as a stream of bytes, similar to how data in file is accessed. The
datagram-based socket uses the UDP (uniform datagram protocol) protocol,
and data is read and written in discrete units called datagrams. The socket
we use is a stream one.
xxvi
3.1.11. BufferSize Property
This property is used only for stream based (TCP) sockets. It
specifies the amount of memory, in bytes, that should be allocated for the
socket’s send and receive buffer.
3.1.12. Binary Property
This property determines how data should be read from the socket.
If set to a value of True, then the data is received unmodified. If set to False,
the data is interpreted as text, with the carriage return and linefeed characters
stripped from the data stream. Each receive returns exactly one line of text.
3.2. Methods of Windows Socket Control
Methods are predefined functions used to perform various tasks on the control.
There are methods that open and close a connection and methods that accept a request
for the connection. The following are the most important ones of them:
3.2.1. Accept Method
The Accept Method is used for the TCP server applications only. It accepts
the request for connection from client system. For the Accept Method to be used, the
control must be in a listening state. This method is used in conjunction with the
connection request. Example:
Private sub winsock connection request (ByVal request ID as integer)
Winsock (Numsockets).Accept request ID
End sub
xxvii
3.2.2. Close Method
This method is used to terminate a TCP connection.
Syntax:
Winsock.close
3.2.3. Listen Method
The Listen Method is invoked on the server application to have the server
application wait for a TCP request for connection from client system.
Syntax:
Winsock.listen
3.2.4. Connect Method
The Connect Method requests a connection to remote computer according
to host name and remote port.
Winsock.connect
3.3. Events
Events are triggers that invoke the methods. The winsock control generates
events that also can be used. Some of these events, such as the connection request,
happen at the server as a result of an action taken by the client. The events generated
by the winsock control make it possible for an unattached system to participate in a
network communications.
xxviii
3.3.1. Read Event
The Read Event is generated when data is available to be read.
Syntax:
Sub winsock-read ([[ index as integer,]] datalength as integer)
3.3.2. Disconnect Event
The Disconnect Event occurs when the remote computer closes the
connection.
Syntax:
Winsock-disconnect (index as integer)
3.3.3. Connect Event
The Connect Event occurs after the connection with remote computer has
been made.
Syntax:
Private sub winsock-connect (index as integer)
End sub
xxix
CHAPTER 4
ALGORITHM USED
Knowing sockets, protocols, and network programming does not mean that you can
easily create a chat server. How you are going to send and receive data. What kind of
synchronization exists between the server and the client application. This chapter will
show you how this server is build and what algorithm it follow, try to enjoy what you
are reading.
xxx
4.1. Project Structure
Since we are using the TCP/IP facilities, we are obliged to divide the project
into two applications. In the next few sections we are going to explain how these
applications works and how they are synchronized with each other.
4.1.1. Control Strings
A set of “Control Strings” was created, such that whenever the client or the
server receives one of these control strings, it should do a certain task. To distinguish
these strings from normal strings (chatting sentences) they are given the following
format: “*ControlCommand “.
For example if the client sends to server the string “*Out walid”, the server upon
receiving this message, the message parsing operation starts. It looks at the first
character if it is a “ * ” immediately it recognizes that this is a control string. It
continues parsing until it reads the control command which is in this case “ Out “. It
matches this control to the group of commands it has. Where it finds out that this
client ( walid ) is trying to disconnect himself, so the function “ User_Out ” is called
where the disconnection operation is completed. Else if the string does not begin with
a star, then it is a normal string and therefore it should be broadcasted to other
connected users to be displayed in their public window. In fact there are many
controls in both server and client where each has its own job and some of these
controls are common between both server and client.
xxxi
4.1.2. Client
The client form is divided into four sections. A text box of the username, a
text box of the host where the server application is running, another text box of the
public sent data, and a list of the connected users. To get connected to server you just
enter a username, the host name you want to connect to, and finally hit the connect
button figure 4.1.2.1. shows the client form.
Figure 4.1.2.1 Client Form
During this connection operation, the client will send a control “*In username”
indicating to the server that there is a new chatter. The server will parse this string and
call the “User_In” function which adds this username to his list and retransmit another
identical control string to all connected users containing all the online usernames in
Connect button
Users on line
Received DataUser status
xxxii
order to update the “connected users list” in the client’s form. The same thing
happens when the user wants to disconnect himself where instead of sending “*In
username”, “*Out username” is sent and “User_Out” function is called which
disconnects the user and do all the updates.
4.1.3. Server
Till now it is clear that the server application has dual job, one to receive
data and another to transmit data. In fact it plays the role of a “ traffic officer ”
( putting everything in order the right order ). Since all the chatting operations are
passed through the server, then the main job of server is responding to the control
strings sent by clients as we have seen in the “in” and “out” requests. Figure 4.1.3.1
shows the server form.
Figure 4.1.3.1. server form
Number of connected
Users on line
Connected Users
Encrypted Data
xxxiii
It plays an important role during the private chatting as we are going to see in the next
chapter.
4.2. Private chatting
When ever a client wants to initiate a private session, in the list of connected
users, he double clicks the username he wants to chat with. Two phenomenon will
take place. First, open a local-private session window. Second, to tell the server that
he wants to chat privately in order to open a remote private window. When these
conditions are satisfied, private chatting can be practiced by just writing in the send
text box and then hitting the enter button in your keyboard. Figure 4.2.1. shows the
private session form.
Figure 4.2.1. private session form
Private Data
Terminate Private Session
Send Data
Data To be Send
Destination Client
xxxiv
CHAPTER 5
PROBLEMS ENCOUNTERED
To say, “I am going to write a chat application without having problems” means that
you are not really working with that application. In our previous four chapters, our
main concentration was to show and explain network programming, sockets and how
do they work. Now, considering that all the needed information was properly
delivered for you, it is time to shake your brain neurons and start solving problems.
xxxv
5.1. Multi-user
For two programs to use the TCP/IP facilities, one should take the role of client
and the other should take the role of server. The client initiates a socket and tries to
send a connection request on that port. For the connection to take place, the client
should be on the connection mode and the server should be on the listening mode.
Supposing that all the required conditions for a connection are satisfied and
both applications are ready to establish that connection. The first client sends a
connection request for the server that is in the listening mode so it detects a
connection. It accepts that connection and the socket shifts itself from the listening
mode to the connected mode. Now another user enters and sends another connection
request for the server. Automatically, this request will be rejected since the server is in
the connected mode and it should be in the listening mode. So, what shall we do in
order to allow other users to connect to server?
5.2. How To Allow Multi-user
Following an extensive research and reading, it seems that Biology in general
and cloning in specific is the solution. What is cloning? And how are we going to use
it?
Cloning: a group of cells or organisms, derived from a single ancestral cell or
individual and all genetically alike.
In fact, we are not going to use genes and cells. All what we are going to do is
to create a socket with all its parameters. Each time a client requests a connection, the
server clones from that socket and provides the client with a socket descriptor (like
xxxvi
array structure) so the operation works likes this. When the server application first
runs, it creates an array of sockets and puts the socket of index zero in the listening
mode. When a client requests a connection, the connection will be accepted (since
socket [0] is listening) immediately. The server takes that connection that was caught
by socket [0] and scans other socket indexes for available sockets. The time it finds a
socket descriptor, it puts that client on that socket, updates the number of last socket
being used, and returns to listening mode at socket [0] such that when another user
tries to access the server, he will be accepted as shown in (figure 5.2.1.). Since all the
connection operations take place in Accept event, the code should look like this:
Private sub socket-accept (index as integer, socket id as integer)
Dim 1 as integer
For I = 1 to last socket
If not socket [I]. connected then Exit for
Next I
If I > last socket then
Last socket = last socket + 1 : I = last socket
Load socket (I)
End if
Socket [I].address family = AF-INET
Socket [I].protocol = IPPROTO – IP
Socket [I]. sockettype = sock-stream
Socket [I]. binary = true
Socket [I]. buffersize = 1024
Socket [I]. blocking = false
Socket [I]. accept = socket id End sub.
xxxvii
figure 5.2.1. MultiUser
xxxviii
5.3. Private chatting
Another facility of our chat server is the private chatting. Whenever you are
connected to a server, you will have two kinds of chatting; public chatting (your
messages appears to all users on-line) and private chatting (exchange of data between
clients privately). By default, you will be connected to a public window, plus another
window containing all the users on-line with you. Private chatting is initiated by
double clicking on the user name in the list. Immediately a small window between
you and the remote client appears indicating that you are in the private mode and that
you can start chatting.
5.4. Keep track of users
In fact, we have two kinds of private chatting; DCC that is a direct IP to IP
connection and another one where all the messages pass through a server which
has the job of delivery. In our system, we will use the server technique, but the
problem here is the delivery process and how it works. Therefore the server
should know each user, to which socket they are connected, and the available
window number.
5.5. How To Keep Track Of Users
To keep track of a user and on which socket he is connected, we maintain a
data base made up of one table containing two fields; username and socket
number. Each time a user is connected to a server, his username and socket
number are added to database automatically. Whenever the user double clicks a
xxxix
username to run the private chatting, the server fires a query that selects the
destination socket number (according to usernames) and the source socket
number. It sends the destination socket to source and the source socket to the
destination. From that time on, these socket addresses are contcatinated with the
sent message and passed by the server such that it knows where it comes from and
where it should go.
5.6. Private window
To chat privately you should have two windows one on the source client’s
screen and the other on the destination client’s screen. The problem is where does
these windows come from, on which bases they were created, and if I send a
message to which opened window on the screen it belongs.
5.6.1. Open Window
As a matter of fact we have created three identical forms for private
chatting and each of which has its own identity number i.e. form1, form2, form3.
When a client asks for private session, the system will call a function “
choose_window “. This function contains an array of type integer, where the
indexes of this array are equivalent to the identity number of forms, so it scans the
array, if it contains “1” (window is in use) it skips that window and jump to next
window, if it is “0” (window is available) it exits the function and return the index
of that available window to client to open it and the identity window number is
stored in a variable in that opened window. The same thing happens for the
xl
remote window but here the order to open a window comes directly from the
server.
5.6.2. Keep Track Of Windows
When the open window in the source client ends and before sending the
first message, the source client waits an acknowledgment control string from the
server containing in it the window number that was opened in the destination
client’s screen. The next time it receives that number, it calls a function
“First_Message” which has the responsibility of sending the first message where
the destination socket number and the destination window number are attached to
that first message such that when the destination client receives this message, he
parse it and know the window number from which it comes. Now each time a
private message are exchanged these variables are concatenated with it.
xli
CHAPTTER 6
ENCRYPTION
Data being sent over communication lines may be protected by scrambling the
message-that is, putting them in code that can be broken only by the person receiving
the message. After completing the private chatting, its time to deal with encryption or
decryption, where two users can chat privately without fearing that their words are
published to others.
xlii
6.1. Data Encryption / Decryption
We are living in the information age. Computer thrive on information, with
more and more data being obtained and processed every day. Data about you, your
business, your bank account, your bills, and your credit is being processed everyday.
Information is a commodity that is sometimes valued more than gold and silver, and
that’s not likely to change any time soon.
Most information is freely accessible, available to anyone who wants it. The
internet is the world’s largest source of information, an unlimited amount of data that
is, for the most part, free for the asking.
But some information is not meant for public eyes and has to be secured, lest
it fall into the wrong hands. Details of military operations, financial information,
medical records, and som forms of communication are all type of information that
need to be kept secret. This is where data encryption (also known as cryptography)
comes in.
Data encryption is nothing new. it goes back to ancient civilization that used
hieroglyphic to build messages. We’re all familiar with the strange symbols used by
the ancient Egyptians. These hieroglyphics were an early form of encryption, and a
relatively good one. It wasn’t until the Rosetta stone was found in the recent times
that these hieroglyphics could be accurately deciphered. Although data encryption
has always been important, never has it been as necessary and widespread as it is
today.
xliii
A wide range of encryption techniques have been devised, Some are simple,
whereas others are incredibly complex. Obviously, the simpler the encryption
techniques. The easier it is to “crack“. Also, as computers get faster and more
efficient, they become more capable of cracking existing encryption techniques.
Therefore, newer and better methods of encrypting data are constantly being invented.
And, since in our project the main concern is on network programming and not
encryption, we are going to use a simple way of encryption (as demonstration) which
is the XOR encryption.
6.2. XOR Encryption
One simple way to encrypt and decrypt data is by using the XOR Encryption
method. basically. The characters in the data stream and those of code key are
XORed together to create and encrypted character. The process is exactly the same
for data being decrypted.
The code key is a string made up of any alphanumeric characters you want to
use. It can be any number of characters long, but the longer the key is, the more
secure the encryption.
XOR Encryption is not a tight method of encryption, meaning that it can be
broken relatively easily. However, if you want to encrypt messages or documents so
that they cannot be viewed with text editor or browser, then XOR Encryption offers a
simple way to do so
xliv
The following code shows a function called XOREncryption that can be used for both
encryption and decryption. You need only pass it the key (a string) and the data to be
encrypted or decrypted.
Public Function XOREncryption ( strCodekey As string, strDataIn As string) As
string
Dim IonDataPter As Long
Dim intXORValue1 As Integer
Dim intXORValue2 As Integer
Dim strDataOut As string
For IonDataPtr = 1 To Len (strDataIn)
‘ the first value to XOR comes from the data to be encrypted
intXORvalue1 = Asc(Mid$(strDataIn, IonDataPtr, 1))
‘ the second value to XOR comes from the code key.
intXORvalue2 = Asc(Mid$(strCodeKey, ((LonDataPter Mod
Len(strCodeKey))+1, 1))
‘ the two values are XORed together to create a decrypted character.
StrDataOut = strDataOut + Chr(intXORValue1 Xor intXORValue2)
Next IonDataPtr
‘ the XOREcryption function returns the encrypted or decrypted data.
XOREncryption = strDataOut
End Function
xlv
To make the XOREncryption in our application more complex, I avoided using the
same constant key each time the private chatting is fired. Instead, whenever a user
double clicks another username for private chatting the source will automatically
create a random alphanumeric key of 15 characters and has the following format. Six
digits constitute the hour, minutes, seconds when the source user enters the server.
The rest nine characters are random characters generated by source also. When key
generated and before sending the first message to destination, the sources sends that
key to server and server send it to destination where it is used during that private
session. For more security and since the key will pass through the server without
being encrypted, the possibility of cracking this key becomes higher. To overcome
this problem, we have created a function that is called by one of the clients where
after each unit of time say ten minutes it will generate another key and send it to the
other chatter in such a way if a hacker cracks the key after ten minutes another key
will be generated and the hacker will spend his time cracking only.
xlvi
CONCLUSION
As a matter of fact this project took me one year to be completed and this year is
divided into two sections, six months of collecting information and six months of
writing Visual Basic code.
First, the theoretical section, where I have learned lots of things in networking, such
as the TCP/IP protocol (number one in network protocols) and how it works, windows
sockets, and network programming which is one of the best programming domains in
computers.
Second, the technical section which let me become more familiar with a new
programming language such as Visual Basic and its network components.
Having a chat server as a senior project, obliged you and indirectly to go into the tiny
details in networking and no one will teach you these details. Lots of experience was
gained and another beautiful face of networking was discovered.
The psychological part I have learned from that project is that, nothing in life comes
easily and at the same time nothing is impossible only it needs time, patience, and
hard working.
Finally I would like to thank my university N.D.U and all my instructors for helping
me to reach this level.
xlvii
REFERENCES
Books Used
1. James Martin, [1989], “ Local Area Network Architecture and Implementations “.
2. H. L. Capron, [1996], “ Computers Tools For an Information age “.
3. Rob Thayer, [1998], “ Visual Basic 6 “.
4. Pat Bonner, [1996], “Network Programming With Windows Sockets ”.
5. Catalyst Development Corporation, [1999], “ An Introduction To TCP/IP
programming with windows sockets “.
6. Charles L. Hedrick, [1987], “ Introduction To Internet Protocols “.
7. Greg Perry, [1998], “ Sams Teach Yourself Visual Basic 6 In 21 Days “.
8. Star Dust Technology, [1997], “Introducing Windows sockets version 2 “.
9. Novel Education, [1997], “ Course 200 Networking Technologies “.
Software Used
1. Visual Basic 6
2. Socket Wrench Control
3. Microsoft Access 2000