Chat Server
Chat Server
By
Waleed Farah
Fall 2000
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 users 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.
ii
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.
iii
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.
iv
Table of Contents
1. Introduction 1.1. Why Chat Server? 1.2. Why Visual Basic? 1.3. General OverView 2. Network Programming 2.1. Network application 2.2. Protocol Stacks 2.2.1. TCP 2.2.2. IP 2.3. Service Port 2.4. Sockets 2.4.1. What is WinSock? 2.4.1. How WinSock Works 2.4.3. Family Protocols 2.5. Client Server Application 2.6. Blocking Vs. Non-Blocking 2.7. System Requirement 3. Windows Socket With Visual Basic 3.1. Properties Of Windows Socket Control 3.1.1. Host Name Property 3.1.2. Remote Port Property 3.1.3. Local Port Property 3.1.4. Protocol Property 3.1.5. Action Property 3.1.6. State Property 3.1.7. RecvLen Property 3.1.8. Send Data Property 3.1.9. Address Family 3.1.10. SocketType property 3.1.11. BufferSize Property 3.1.12. Binary Property 3.2. Method of Windows Socket Control 3.2.1. Accept Method 3.2.2. Close Method 3.2.3. Listen Method 3.2.4. Connect Method 3.3. Events 3.3.1. Read Event 3.3.2. Disconnect Event 3.3.3. Connect Event 4. Algorithm Used 4.1. Project Structure 4.1.1. Control String 4.1.2. Client 4.1.3. Server 1 2 2 3 4 5 5 6 6 7 7 8 8 10 10 11 12 13 14 14 15 15 15 16 16 17 17 17 17 18 18 18 18 19 19 19 19 20 20 20
21 22 23 24
4.2. Private Chatting 5. Problem Encountered 5.1. Multi User 5.2. How To Allow Multi User 5.3. Private Chatting 5.4. Keep Track Of Users 5.5. How To Keep Track Of Users 5.6. Private Chatting 5.6.1. Open Window 5.6.2. Keep Track Of Windows 6. Encryption 6.1. Data Encryption/Decryption 6.2. XOR Encryption Conclusion References
25 26 27 27 30 30 30 31 31 32 33 34 35 38 39
vi
List Of Figures
Figure 4.1.2.1. Figure 4.1.3.1. Figure 4.2.1. Figure 5.2.1 Client Form Server Form Private Form Multi Users 23 24 25 29
List Of Tables
Table 2.4.1. Windows Socket Layer Table 3.1.1. Server States 9 16
vii
CHAPTER 1 INTRODUCTION
In this chapter we are going to deal with the major points behind choosing a chat server as a senior project and why visual basic is the programming language I choose, with a general overview about the project and how it works. So turn this page quickly and get yourself ready to find how it is working.
viii
locations. Such that it crosses time zones, can reach many people, and reduce the paper flood.
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.
ix
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; everyone 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.
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.
xi
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.
xii
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
xiii
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.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 PCs 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
xiv
systems for the last 3 years. It is now set to become the definitive applications interface for all windows-based communication-capable applications.
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.
xv
to establish a connection with the other program. Table 2.4.1. shows how winsock works
TCP/IP SPI
(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?
xvi
xvii
xviii
associated network event completion. It is highly recommended that in WinSock application to use the non-blocking mode as my application does.
xix
can obtain further information about this update by searching the KnowledgeBase on the Microsoft website.
xx
CHAPTER 3
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 Windows 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.
xxi
xxii
xxiii
Constant SckClosed SckOpen SckListening SckConnection Pending SckResolving Host SckHost Resolved SckConnecting SckConnected SckClosing SckError
Value 0 1 2 3 4 5 6 7 8 9
Description Default Open Listening Connection Pending Resolving Host Host Resolved Connecting Connected Closing Error
xxiv
xxv
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
xxvi
3.2.4.
Connect Method
The Connect Method requests a connection to remote computer according
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.
xxvii
xxviii
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.
xxix
xxx
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.
Users on line Connect button 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
xxxi
order to update the connected users list in the clients 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.
Connected Users Number of connected Users on line
xxxii
It plays an important role during the private chatting as we are going to see in the next chapter.
Data To be Send
xxxiii
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.
xxxiv
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?
xxxv
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.
xxxvi
xxxvii
xxxviii
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.
xxxix
remote window but here the order to open a window comes directly from the server.
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.
xl
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.
xli
Most information is freely accessible, available to anyone who wants it. The internet is the worlds 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. Were 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 wasnt 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.
xlii
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.
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
xliii
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
xliv
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.
xlv
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.
xlvi
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
xlvii