넥슨별의 여행자.....


























'사이버탐험기' 카테고리의 다른 글

넥슨별! 이제 슬슬.....  (0) 2010.02.07
WOW 막막한 퀘스트......  (0) 2010.02.06
에버플레닛... 준비운동..  (0) 2010.01.30
넥슨별 여행.....  (0) 2010.01.30
저랩의 와우(The World of warcraft) 방황기  (0) 2010.01.30

Eclipse Java IDE - Tutorial

Lars Vogel

Version 1.6

30.12.2009

Revision History
Revision 0.118.07.2007Lars Vogel
Created.
Revision 0.2 - 0.718.05.2008Lars Vogel
Several reworks.
Revision 0.7.113.04.2009Lars Vogel
Added Shortcut
Revision 0.825.05.2009Lars Vogel
Update to Eclipse 3.5 (Galileo)
Revision 0.921.06.2009Lars Vogel
Moved Shortcuts to own article under http://www.vogella.de/articles/EclipseShortcuts/article.html
Revision 1.022.06.2009Lars Vogel
Moved Debugging to own article under http://www.vogella.de/articles/EclipseDebugging/article.html
Revision 1.128.06.2009Lars Vogel
Re-org article, own chapter for update manager, simplified views / editor description
Revision 1.212.07.2009Lars Vogel
Screenshot for link with editor
Revision 1.318.07.2009Lars Vogel
Added link to example with jars, changed from XML templates to Java template
Revision 1.402.08.2009Lars Vogel
more details on first Java program
Revision 1.501.11.2009Lars Vogel
Renamed first project, added details for jar handling
Revision 1.630.12.2009Lars Vogel
fixed package name in Java program outside Eclipse

Eclipse Java IDE

This article describes the usage of Eclipse as a Java IDE. It describes the installation of Eclipse, the creation of Java programs, the usage of external jars, quick fix and content assist and the usage of the Eclipse update manager.

This article is based on Eclipse 3.5 (Eclipse Galileo).


1.Eclipse Overview

Eclipse an open source community whose projects building tools and frameworks for creating general purpose application.

The most popular usage of Eclipse is as a Java development environment which will be described in this article.

2.Getting started

2.1.Installation

Download "Eclipse IDE for Java Developers" from the website Eclipse Downloads and unpack it to a directory. This is sufficient for Eclipse to be used; no additional installation procedure is required.

Tip

Use a directory path which does not contain spaces in its name.

Tip

Eclipse requires an installed Java Runtime. I recommended to use Java 6 (also known as Java 1.6).

2.2.Start Eclipse

To start Eclipse double-click on the file eclipse.exe in your installation directory.

The system will prompt you for a workspace. The workspace is the place there you store your Java projects (more on workspaces later). Select a suitable (empty) directory and press Ok.

Eclipse will start and show the Welcome page.

Close the welcome page by press in little x besides the Welcome.

3.Eclipse UI Overview

Eclipse provides perspectives, views and editors. Views and editors are grouped into perspectives. All projects are located in a workspace.

3.1.Workspace

The workspace is the physical location (file path) you are working in. You can choose the workspace during startup of eclipse or via the menu (File-> Switch Workspace-> Others).

All your projects, sources files, images and other artifacts will be stored and saved in your workspace.

Tip

To predefine the workspace you can use the startup parameter -data path_to_workspace, e.g. c:\eclipse.exe -data "c:\temp" Please note that you have to put the path name into brackets.

Tip

To see the current workspace directory in the title of Eclipse use -showLocation as additional parameter.

3.2.Perspective

A perspective is a visual container for a set of views and editors.

You can change the layout within a perspective (close / open views, editors, change the size, change the position, etc.)

Tip

A common problem is that you closed a view and don't know how to re-open this view. You can reset a perpective it to it original state via the menu "Window" -> "Reset Perspective".

Eclipse allow you to switch to another perspective via the menu Window->Open Perspective -> Other.

For Java development you usually use the "Java Perspective".

3.3.Views and Editors

A view is typically used to navigate a hierarchy of information or to open an editor. Changes in a view are directly applied.

Editors are used to modify elements. Editors can have code completion, undo / redo, etc. To apply the changes in an editor to the underlying resources, e.g. Java source file, you usually have to save.

4.Create your first Java program

The following will describe how to create a minimal Java program using Eclipse. It will be the classical "Hello World" program. Our program will write "Hello Eclipse!" to the console.

4.1.Create project

Select from the menu File -> New-> Java project. Maintain "de.vogella.eclipse.ide.first" as the project name. Select "Create separate source and output folders".

Press finish to create the project. A new project is created and displayed as a folder. Open the folder "de.vogella.eclipse.ide.first"

4.2.Create package

Create now a package. A good convention is to use the same name for the top package as the project. Create therefore the package "de.vogella.eclipse.ide.first".

Select the folder src, right mouse click on it and select New -> Package.

4.3.Create Java class

Right click on your package and select New -> Class

Create MyFirstClass, select the flag "public static void main (String[] args)"

Maintain the following code.

				package de.vogella.eclipse.ide.first;public class MyFirstClass {	public static void main(String[] args) {		System.out.println("Hello Eclipse!");	}}			

4.4.Run your project in Eclipse

Now run your code. Right click on your Java class and select Run-as-> Java application

Finished! You should see the output in the console.

4.5.Run your Java program outside Eclipse (create jar file)

To run your Java program outside of Eclipse you need to export it as a jar file. Select your project, right click on it and select "Export".

Select JAR file, select next. Select your project and maintain the export destination and a name for the jar file. I named it "myprogram.jar".

Press finish. This will create a jar file in your select output directory.

4.6.Run your program outside Eclipse

Open a command shell, e.g. under Microsoft Windows select Start -> Run and type in cmd. This should open a consle.

Switch to your output directory, e.g. by typing cd path, e.g. if you jar is located in "c:\temp" type "cd c:\temp".

To run this program you need to include the jar file into your classpath. See Classpath and Java JAR Files for details.

				java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass			

Congratulations! You created your first Java project, a package a tiny Java program and you ran this program inside Eclipse and outside

5.Content Assists and Quick Fix

Tip

For a list of the most important Eclipse shortcuts please see Eclipse Shortcuts

5.1.Content assist

The content assistant allows you to get input help in an editor. It can be invoked by CTRL + Space.

For example type syso and then press [Ctrl + Space] and it will be replaced by System.out.println(""). Or if you have an object, e.g. Person P and need to see the methods of this object you can type p. (or press CTRL + Space) which activates also the content assist.

5.2.Quick Fix

Whenever there is a problem Eclipse will underline the problematic place in the coding. Select this and press (Ctrl+1)

For example type "myBoolean = true;" If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press "Ctrn+1", then Eclipse will suggest to create a field or local variable.

Quick Fix is extremely powerful, it allows you to create new local / field variables, new methods, classes, put try and catch around your exceptions, assign a statement to a variable etc.

6.Using jars (libraries)

6.1.Adding external library (.jar ) to the Java classpath

The following describes how to add external jars to your project.

The following assumes you have a jar available.

Tip

If you need an example for working with jars you can use JFreeChart Tutorial

Create a new Java project "de.vogella.eclipse.ide.jars". Create a new folder called "lib" (or use your existing folder) by right click on your project and selecting New -> Folder

From the menu select File -> Import -> File system. Select your jar and select the folder lib as target.

Select your project, right mouse click and select properties. Under libraries select "Add JARs".

The following example shows how the result would look like if junit-4.4.jar would be added to a project.

6.2.Show source code for jar

To browse the source of a type contained in library you can attach a source archive or source folder to this library. The editor will then show the source instead of a the decompiled code. Setting the source attachment also allows source level stepping with the debugger.

The Source Attachment dialog can be reached via:

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Source attachment attribute and press Edit

Maintain the location to the source attachement.

In the Location path field, enter the path of an archive or a folder containing the source.

6.3.Add the Javadoc for a jar

Download the javadoc of the jar and put it somewhere in your filesystem.

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Javadoc location attribute and press Edit

Maintain the location to the api.

7.Updates and Installation of Plugins

7.1.Eclipse Update Manager

Eclipse provides functionality via so-called features (which contain plugins). Eclipse 3.5 contains a Software Update Manager which allows you to update existing plugins and to install new plugins.

To update your existing installation select the menu Help -> Check for Updates. The system will verify if for the installed plugins updates are available or not.

To install new functionality, select Help-> Install New Software.

Select from the list a update site from which you would like to install new software. For example if you want to install new plugins from Galileo select the Galileo Update Site.

Tip

Sometimes you have to uncheck "Group items by category" – not all available Plugins are categorized. If they are not categorized they will not be displayed. See Eclipse bug .

To add a new update site select, press the button "Add" and input the URL. This will then make this update site available and will allow you to install software from this site.

7.2.Manual installation of plugins (dropins folder)

If you’re using Plugins where no Software Site is available, then you can use the Dropins folder in your Eclipse installation directory.

To do this put the plugin into Eclipse "dropins" folder and restart Eclipse. Eclipse should detect the new plugin and install it for you.

8.More Tips

8.1.Problems view

The problems view displays problems in your projects. You can open it via Windows -> Show View -> Problems

You can configure the problems view, e.g. if you only want to display the problems from the current selected project, select "Configure Contents".

8.2.Important Preference Settings

Eclipse allows to set semicolons (and other elements) automatically.

Eclipse allows to format the source code and to organize the imports at save.

Tip

You can export your Preferences settings from one workspace via File -> Export -> General -> Preferences. Similar you can import them again into your workspace.

8.3.Task Management

If you use // TODO in the coding this indicates a task for eclipse and you find it in the task view of Eclipse.

For more advanced tasks you can use Eclipse Mylyn Tutorial .

8.4.Working Sets

A common problem in Eclipse is that your data in your workspace grows and therefore your workspace is not well structured anymore. You can use working sets to organize your displayed projects / data. To setup your working set select in the Package Explorer -> Show -> Working Sets.

Press new on the following dialog to create a working set.

On the following dialog select java, select the source folder you would like to see and give it a name. You can now easily display only the files you want to see.

8.5.Synchronize package explorer with code display

The package explorer allows to display the associated file from the current selected editor. Example: if you working on foo.java and you change in the editor to bar.java then the display in the package explorer will change.

To activate this press "Link with Editor".

8.6.Code Templates

If you have to type frequently the same code / part of the d0cument you can maintain templates which can be activate via autocomplete (Ctrl + Space).

For example lets assume you are frequently creating "public void name(){}" methods. You could define a template which creates the method body for you.

To create a template for this select the menu Window->Preferences and Open Java -> Editor -> Templates

Press New. Create the following template. ${cursor} indicates that the cursor should be placed at this position after applying the template.

This this example the name "npm" is your keyword.

Now every time you type the keyword in the Java editor and press Ctrl+Space the system will replace your text with your template.

9.Next steps

To learn how to debug Eclipse Java programs you can use Eclipse Debugging

To learn Java Web development you can use with Servlet and JSP development with Eclipse Web Tool Platform (WTP) - Tutorial . If you want to develop rich stand-alone Java clients you can use Eclipse RCP - Tutorial

. Check out Eclipse Plugin Development - Tutorial to learn how to develop your own plugins.

Good luck in your journey of learning Java!

10.Thank you

Thank you for practicing with this tutorial.

Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.

11.Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.

I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.

12.Links and Literature

에버플레닛... 준비운동..




넥슨별 여행.....



저랩의 와우(The World of warcraft) 방황기

그냥 돌아댕기기...



'사이버탐험기' 카테고리의 다른 글

에버플레닛... 준비운동..  (0) 2010.01.30
넥슨별 여행.....  (0) 2010.01.30
SL 탐험기 2010.01.24 세컨드라이프라니...  (1) 2010.01.24
저랩의 와우이야기1  (0) 2010.01.23
넥슨의 별나라 이야기!!!!!  (0) 2010.01.23

Developing open source Java applications with java.net and Eclipse

Part 1 - Creating a new project in Eclipse


Martin Pllu
martinpllu-AT-dev.java.net

Introduction


This series of tutorials show how Eclipse can be used to develop open source Java applications hosted on java.net. The target audience is developers who have a working knowledge of Java, but are new to Eclipse.


If you have any questions or feedback, please use the tutorial's discussion forums.


Today we'll see how to create a new project in Eclipse. Even if you don't need to do this (for example, if you plan to contribute to an existing project), I'd recommend that you follow along. The tutorial introduces some important Eclipse concepts.

In Part 2 we'll cover Team development with Eclipse and CVS.

Before we start the tutorial, let's look at some of the key features of Eclipse and java.net.

Key features of Eclipse


Eclipse provides a powerful and feature rich integrated development environment (IDE) for Java. To get an idea of what it can do, skim through the links below (from the online Eclipse help).
If you haven't used an IDE before, or last used one a few years ago, please check Eclipse out. You'll be amazed by its ease of use and advanced development features. I switched to Eclipse after years of developing in Emacs, and it's made me much more productive. It's worth using for the automated refactoring support alone!

Eclipse runs on Windows, Linux, Mac OSX, Solaris, AIX and HP-UX. It's written in Java, but uses a graphical toolkit called SWT. This toolkit is a Java wrapper for native platform widgets, and it produces a very slick look and feel.

Eclipse is actually a generic application platform with a sophisticated plugin architecture - the Java IDE is just one set of plugins. You can develop your own plugins, or use Eclipse as a basis for "rich client" applications, e.g. a web browser or a money manager. See the Platform Plug-in Developer Guide for more.

Eclipse is free open source software developed by the independent Eclipse Foundation, which is backed by industry heavy hitters such as IBM Rational, Borland, Red Hat, and SuSE. Its open source pedigree has made it ideal for open source development. For example, its built-in CVS client GUI (covered in Part 2) makes it a snap to work with CVS hosting sites like java.net.

The Eclipse d0cumentation is excellent - see the main website and the online help.

There's an active community of third party Eclipse plugin developers, both open source and commercial. Good plugin directories are available here and here. As an Eclipse user, you're regularly rewarded with great new features from official Eclipse releases and from the plugin development community.

Key features of java.net


java.net is a thriving online Java community featuring news, articles, forums, wikis, and hosting for many open source projects. It was founded in 2003 by Sun Microsystems to help encourage open source Java development, however (like the Eclipse Foundation) java.net is completely independent. A number of communities have been formed on java.net to cater for different technologies and interests, for example Java Tools, Java Enterprise, Jini, and Java Linux. Some communities such as Javapedia and Global Education and Learning are great places to learn about Java and to share knowledge. It's the communites that really set java.net apart from other development hosting websites (like sourceforge).

It's easy to set up a new project - all you need is a good idea and the Project Request Forms. You can browse the online project directory which includes both projects hosted at java.net and linked projects (which are hosted elsewhere but affiliated with java.net). Before starting a new project, please look at the existing projects to make sure that you're not reinventing the wheel. If your idea can be used to enhance an existing project, the end result is often better than several similar, but incompatible, projects. If you want to contribute to an existing project, speak to the owners listed on the project's website.

java.net uses CVS for version control of source code. If you haven't used CVS before, don't worry, Part 2 will give you a step-by-step guide. There's a Web interface for viewing the contents of files checked into CVS, for example see here. This is handy for linking to code or d0cumentation in CVS.

A number of useful tools are provided to help you work as part of a team, for example issue trackers, announcement boards, discussion forums, and mailing lists. Project owners can easily administer project memberships and roles. As a project member, you can choose to be notified by email whenever a project change is made, for example CVS checkins, new discussion forum entries, etc. RSS feeds are also available so that anyone can keep an eye on your project. Project webpages are easy to set up - you just check HTML into CVS. A good search engine is also provided for project-specific or site-wide searches.




Tutorial Part 1 - Setting up a new project in Eclipse


The instructions in this tutorial are based on Eclipse 3.0. Later versions of Eclipse 3.x may vary slightly.



In today's tutorial, we'll be working with Eclipse to create and configure a new Java project. We won't be working with java.net until the next instalment.

Prerequisites

  • Download Eclipse 3.0 or later from here.
  • Java 1.3 or later is required. If you don't already have a suitable Java installation, download one from http://java.sun.com.

If you have problems downloading or starting Eclipse, see the Eclipse FAQ.

Starting Eclipse


For the purposes of the tutorial, I'm going to set up a project called javatools-demo.

First start up Eclipse and supply a path to a new folder which will serve as your workspace. The workspace is a folder which Eclipse uses to store your source code.



Avoid checking the "Use this as the default..." box, which will always start up Eclipse with the same workspace. You'll probably find it useful to be able to switch between different workspaces on startup.

When Eclipse starts, you'll see the Welcome page:



Getting help


Note that you can access Eclipse help at any time via Help->Help Contents. This is the same as the help on the eclipse.org website.

Creating a project


Close the Welcome page. Right-click in the Navigator panel, and select New->Project:





Select "Java Project" and then "Next". Enter the name of your project:



Click "Finish". If you get prompted about switching to the Java perspective, select "Yes".

Perspectives

Eclipse provides a number of perspectives for different types of development task. You can see all of the available perspectives by selecting Window->Open Perspective->Other...



The "Java" perspective (which we're currently in) provides editors, views, and menu items which are useful for developing Java applications. The "Resource" perspective (which we started off from) provides a more basic set of tools, for example a Windows Explorer style file navigator.

You can quickly switch between perspectives using the buttons to the top right of the Eclipse window:




Note that projects are simply directories stored under the directory that you selected as your workspace. Look on the file system and see for yourself.

Use an alternative JRE


In the Package Explorer panel of the Java perspective, right-click on your newly created project and select "Properties". The Properties dialog opens on Java Build Path, which controls the project's classpath.



For now, the only entry is the JRE System Library shown in the "Libraries" tab. This defaults to the same JRE that was used to run Eclipse. In my case, a Java 5.0 installation was used. Depending on what versions of Java you have installed, you may see a different JRE here.

You might want to use a different JRE, for example the default may be Java 5.0 but you want your project to be compatible with Java 1.4 or 1.3 (your application will be useful to more people if it's backwards compatible with older JREs).


If you're happy with the default JRE, skip to the next section.


Ensure that you have the appropriate JDK or JRE version installed on your machine. If not, download and install from http://java.sun.com.

First click on "Add Library":




Click "Next" and then "Installed JREs..."



Click "Add".

In the next dialog, browse to the JRE or JDK that you want to use, and enter a name:



Click "OK" and then choose the new JRE:



Click "OK" and then "Finish". Your project will now be compiled against the new JRE.



Create source folders


Switch to the "Source" tab in the Properties dialog.



Eclipse projects can contain one or more source folders which contain Java source files. By default, the project directory itself is the only source folder.

Using multiple source folders is a good way to separate different types of code. This can make your project easier to work with and simplifies the Ant build scripts which we'll write later. We're going to set up separate source folders for application code and unit test code.

Click on "Add Folder" and type "src":



Click "Yes" when prompted.



Click on "Add Folder..." again and then "Create New Folder...". This time, call the folder "test". Click "OK" twice.

You'll see that we now have two source folders:



Clicking on "Order and Export" shows you the complete classpath used for compiling any Java source files in the project (we haven't created any source code yet!).

The classpath currently contains the two source folders plus the JRE:

.

Output folder

When you use custom source folders, the compiler stores the generated class files in a separate folder called the "output folder". As you can see from the dialog above, the output folder is set to a "bin" subdirectory under the project. Leave this setting alone unless you have a good reason.

Note that you won't see the bin subdirectory or class files in the Package Navigator by default. Switch to the Resource perspective to see an unfiltered view of all project files and directories.

Import third party JARs


If your application has a dependency on a third party library, you can import it into your project as a JAR file and add it to your project's classpath.

Say that the demo application needs to process dates, and we want to use the excellent Joda Time API.

First download a binary distribution of the library and extract it somewhere on your file system. Then create a new folder in your project as shown below:





When prompted, call the folder "lib". Right click on your new folder and select "Import..."




In the resulting dialog, select "File System" and then "Next". Browse to the location that you extracted the library to and select the JAR file.

Note that when you click "Browse" you must navigate to the directory containing the JAR file, otherwise you'll end up importing some unwanted folders as well as your JAR file.



Click "Finish". You should end up with something like:



Now to add the JAR to the project classpath. Right-click on the project and select "Properties". Go to the "Libraries" tab in "Java Build Path":



Click on "Add JARs..." and navigate to the freshly imported JAR. Click "OK"



Import source code


If you don't have any existing source code to import into Eclipse, skip to the next section.


Import code by right clicking on your project selecting "Import".



If your code is stored in a JAR or ZIP file, choose "Zip file". Otherwise, choose "File System". The rest of the process is pretty self explanatory.

Create a class


If you want to create some new Java code, right-click on the "src" source folder and select "New->Class"



First enter the package that your class belongs to.


Although reversing the domain name is common practise for package names, please DON'T use net.java as a project prefix. See this wiki entry for an explanation..



I've gone for org.jtdemo.

The rest of the dialog is pretty self explanatory. Feel free to experiment...



You should now see your newly created class in an editor window.




Views and editors

Eclipse makes a distinction between views and editors. An editor is a window which directly displays editable content, such as the Java editor above. When you make a change in an editor, the change doesn't take effect until you save the editor. You can tile and layer editors in various ways by dragging their title bars. To see a list of all open editors, press Ctrl-E.

A view is a window which displays a more abstract representation of content, for example the Package Explorer, Problems, and Outline views above. Changes made in a view take effect immediately. You can dock, layer, and tile views is various positions by dragging their title bars. To open a new view, select Window->Show View->Other...

To toggle maximisation of the current view or editor, double-click its title bar or press Ctrl-M.


Now you can start writing code.

Eclipse has so many useful Java development features, I can't do justice to them here. I'll refer you back to Java Development Tooling Tips and Tricks and Base Eclipse Platform Tips and Tricks for a small taste of what's possible. Go ahead and experiment!

Sharing preferences


Almost all of Eclipse's features are in some way configurable via preferences. You may want to share your preferences with other people, for example to enforce a consistent coding style. You may also want to have several workspaces, and use consistent preferences across all of them.

You can export your preferences using the Export... button on the main Preferences dialog (Window->Preferences). This will export your preferences in XML format. Preferences exported in this way can be imported using the Import... button.

Multiple projects, and the Order and Export tab


If required, you can create multiple Java projects and introduce build dependencies between them. Create a new Java project called "other", then look at its build path (right-click, Properties, Java Build Path). You'll see an entry for your original project as show below. Check this to introduce a build dependency.



Now look at the build path of your original project. The "Order and Export" tab contains a list of all entries on the project's classpath. If any of them are checked, they are exported, which means they are automatically added to the classpath of any project which is dependent on this project. For example, if we were to check the joda-time-098.jar entry, it would be automatically added to the classpath of the "other" project.



Note that you can select any entry and use the "Up" and "Down" buttons to change its order in the classpath.

Use a single project for java.net applications

If you're creating an application which you're going to host at java.net, use a single project. This will make it easier to work with CVS.

If you want to keep different parts of your application code separate, use source folders. If want to use a third party Eclipse project ( for example another Eclipse-based project hosted on java.net), use a JAR file containing the project's classes rather than a project dependency.

Installing plugins


Eclipse has a GUI for finding and installing new plugins which can be accessed via Help->Software Updates->Find and install. However, I find it more convenient to install plugins manually as described below.

First, download the plugin that you want to install. As mentioned earlier, there are good online indexes available here and here.

If necessary, extract the plugin from its zipped/tarred form. Look for a directory containing a file "plugin.xml". Copy this directory to the "plugins" directory under your Eclipse installation, for example C:\eclipse\eclipse-SDK-3.0.1-win32\eclipse\plugins. Restart Eclipse and the plugin should be ready to use (sometimes the plugin will provide a new view, editor, or perspective that you'll have to activate manually).

If you're not sure if a plugin is loaded, select Help->About Eclipse Platform, and click "Plug-in Details".



This will show a list of all loaded plugins:



Summary


Hopefully you've now got a feel for what Eclipse is all about, and you know how to set up a project for open source development. In Part 2, we'll look at using Eclipse's CVS integration in conjunction with java.net's CVS repository.

About the author


Martin Pllu is a member of the Messaging & Java Infrastructure Team at the Standard Life Assurance Company in Edinburgh, Scotland. He is the author of a number of open source applications including leafcutter and tracetest, both hosted here at java.net.

SL 탐험기 2010.01.24 세컨드라이프라니...




'사이버탐험기' 카테고리의 다른 글

넥슨별 여행.....  (0) 2010.01.30
저랩의 와우(The World of warcraft) 방황기  (0) 2010.01.30
저랩의 와우이야기1  (0) 2010.01.23
넥슨의 별나라 이야기!!!!!  (0) 2010.01.23
넥슨별 레벨업!!!!  (0) 2010.01.17

게임 서버의 구조 #

참고> 이 글은 [http]한빛 네트워크 에서 퍼왔음을 알려드립니다.

남재욱
(주)지스퀘어 3D 캐주얼 게임 서버 프로그래머

온라인 게임에서 실질적인 게임을 진행시켜주는 것이 게임 서버이다. 우리는 게임 서버의 구조는 게임의 진행과 시스템의 효율성에 많은 영향을 미치는 부분이다. 물리적으로 한정적인 시스템 자원을 효율적으로 사용하기 위해서 다양한 분산 처리는 필수적인 요소이다. 분산 처리 구조를 익힘으로써 우리는 좀 더 세련되고 뛰어난 성능을 발휘할 수 있는 게임 서버를 만들 수 있다. 온라인 게임 서버 프로그래밍의 핵심인 게임 서버의 구조에 대해 알아 보도록 하자.


일반적인 게임 서버 구조 #


게임 서버는 실질적인 게임을 진행하는 역할을 담당한다. 게임 서버는 유저간의 동기화, NPC 의 인공지능, 아이템 시스템 등 게임 시스템의 총 집합이라 할 수 있다. 게임 진행에 필요한 모든 게임의 요소들을 총괄하여 진행시켜주는 작업을 하기 때문에 가장 많은 일을 담당한다. 게임을 진행하는 요소는 방대하기 때문에 하나의 서버에서 처리하는데는 많은 부담이 된다.

게임 서버를 제작하고 테스트를 하는 과정에서 수십명의 유저를 처리하는 것은 그리 문제가 되지 않는다. 더욱이 하드웨어의 눈부신 발전에 힘입어 게임에서도 고성능 서버를 사용하기 시작하면서 서버쪽의 부담이 덜어져 가는 것도 사실이다. 하지만 접속 유저가 늘어나면서 서버쪽에서 느끼는 부하는 그 수치가 급격하게 증가한다. 그렇기 때문에 서버를 제작하면서 게임 서버의 부하를 분산시키려는 노력이 필요하다.

NPC 서버의 분리 #


구성에 따라 게임 서버에 많은 부하를 줄 수 있는 것이 NPC 의 인공지능 부분이다. 보통 게임에서 NPC 의 인공지능은 상당히 단순하게 느껴진다. 하지만 수많은 NPC 의 인공지능을 구성하는 코드는 상당히 복잡하며 처리량도 만만치가 않다. 따라서 <그림 1> 과 같이 NPC 의 인공지능 부분을 따로 분리하여 게임 서버에서 부하를 줄이게 된다.

Article/NPC_Server.gif
<그림 1> NPC 서버의 분리

NPC 서버와 게임 서버가 분리되면 게임 서버에서는 NPC 오브젝트만 생성하게 된다. NPC 서버에서는 게임 서버에서 생성된 NPC 오브젝트의 인공지능을 처리한다. NPC 서버에서는 인공지능 부분만 처리하여 게임 서버에 있는 NPC 오브젝트에게 소켓 통신 등을 이용하여 명령한다. 게임 서버 입장에서는 소켓 통신을 하는 비용은 지불하게 되지만 많은 서버 리소스를 절약하는 효과를 볼 수 있다. 또한 NPC 서버에서는 인공지능 부분을 전담하기 때문에 더욱 복잡하고 똑똑한 인공지능을 만들어 낼 수도 있다. 사실 게임 서버에 인공지능 부분까지 처리하게 되고, 처리할 NPC 의 숫자도 많다면 복잡하고 세련된 인공지능은 서버에 많은 부담을 주게 될 것이다.

온라인 게임을 하다보면 서버가 다운되어 다시 접속을 하였는데 NPC 들이 필드에서 하나도 없는 경우를 몇몇 게임에서 발견할 수 있다. 이러한 상황은 NPC 서버와 게임 서버간의 동기화가 안된 상황에서 클라이언트가 게임 서버에 접속하였을 때 발생하는 현상이다. 이런 경우 잠시만 기다리면 갑자기 NPC 들이 생겨나는 것을 볼 수 있을 것이다.

NPC란? Non-Player Characters 의 약자이다. 게임에서 유저 캐릭터가 아닌 서버에 의해조종되는 캐릭터를 총칭하는 말이다. 온라인 게임에서는 보통 상점주인, 경비병, 몬스터등이 이에 속한다.

동기화 서버의 분리 #


게임 서버에서 제일 기초적인 동작은 캐릭터간의 동기화 작업이다. 동기화 작업은 게임 서버가 시작되고 유저들이 접속하면서 부터 처리하게 된다. 동기화 작업은 제한된 공간에서 유저들의 행동을 상호간에 인지시키게 하기 위한 작업이다. 유저들의 행동을 상호간에 인식시키기 위해서는 모든 캐릭터의 행동을 근처의 모든 캐릭터들에게 알려 주어야 하기 때문에 많은 부하를 발생시킨다. 따라서 동기화 작업만을 전담하는 서버를 분리하여 준다면 게임서버의 퍼포먼스를 향상시킬 수 있다. PC / NPC 간의 동기화 작업은 각각의 오브젝트 단위로 이루어지기 때문에 동기화 서버를 따로 두어 캐릭터들의 동기화 부분만 전담시켜 부하를 분산시키는 구조를 택할 수 있다.

Article/SYNC_Server.gif
<그림 2> 동기화 서버의 분리

동기화 서버는 NPC 와 PC 의 동기화 작업만 전담한다. 게임 서버에서 클라이언트의 움직임 등의 요청을 받는다면 동기화 서버로 명령을 전달하게 되고 동기화 서버에서는 명령에 따른 결과를 게임 서버에 전달하게 되어 게임 서버에서는 결과를 각색하여 클라이언트로 전달하게 된다. 동기화 서버가 분리되는 방식은 게임 서버가 해야할 일을 물리적으로 다른 서버와 분담하여 처리하는 방식이기 때문에 많은 유저가 접속하였더라도 서버의 성능을 일정하게 유지시켜줄 수 있는 구조이다.

채팅 서버의 분리 #


MMORPG 는 다른 측면에서 보았을 때 커뮤니티의 일종으로서 유저 상호간 액션에 의해 게임이 진행된다. 커뮤니티에서 빠질수 없는 것이 의사 소통이며, 게임에서는 채팅을 통해 상호간의 의사전달을 하게 된다. 따라서 게임 서버에서는 유저들의 많은 양의 채팅 메시지를 처리하게 된다. 또한 채팅 메시지는 유저간의 동기화 문제와도 연관되어 많은 부하를 발생시킬 수도 있기 때문에 채팅 서버만을 따로 두어 게임 서버의 부하를 분산시키기도 한다.

Article/Chatting_Server.gif
<그림 3> 채팅 서버의 분리

채팅 서버를 분리하게 되면 대부분 클라이언트와 채팅 서버간의 1:1 통신을 하게 된다. 즉, 클라이언트는 게임 서버와 채팅 서버에 각각의 연결을 만들어 통신을 하게 된다는 것이다. 따라서 게임 서버에서 클라이언트의 PC 가 동기화 영역을 움직인다면 채팅 서버에서도 마찬가지로 해당 채팅 동기화 영역으로 움직여 채팅 메세지 동기화를 하게 된다. 게임 서버에서 할 일이 분산되기 때문에 좀 더 안정적인 게임 서버를 만들수 있게 되지만 채팅 서버에서도 캐릭터의 이동에 따른 기본적인 동기화 작업이 필요하기 때문에 채팅 메세지를 게임 서버에서 처리 하는것보다 좀더 많은 작업량이 필요하게 된다.

참고> 서버 기능 분리시 주의사항서버를 분리하는데에는 많은 사항을 고려해야 한다. 서버의 기능을 나누어 부하를 분산시키는것은 좋지만 서버를 나누어서 새롭게 생겨날 수 있는 취약점이나 또 다른 부하를 고려해야 하기때문이다. 예를 들어 NPC 서버가 분리된다면 게임 서버와 NPC 서버간의 동기화, NPC 서버와게임 서버간의 통신으로 인한 네트워크 오버헤드를 고려해야 한다.동기화 서버가 분리되면 역시 동기화 서버와 게임 서버간의 통신으로 인한 네트워크 오버헤드와게임서버와 동기화 서버의 권한을 명확히 해야 한다. 채팅 서버가 분리 된다면 채팅 서버와 게임서버간의 동기화 문제를 고려해야 한다.


분산 게임 서버의 구조 #


서버 프로그래밍을 하다 보면 분산 서버 또는 클러스터링에 많은 관심을 갖게 된다. 그 이유는 온라인 게임 서버 프로그래머라면 누구라도 기술적 한계를 뛰어넘어 수만에서 수십만명이 하나의 월드에서 자유롭게 게임을 즐기는 환경을 만들어 주는 것을 바라기 때문이다.

현재 국내 온라인 게임을 살펴보면 월드에는 일정한, 내부에서 정하는 유저 제한치가 존재하게 되며 이러한 제한치가 넘어가게 되면 더이상의 유저를 수용하기 보다는 다른 서버군을 오픈하여 유저의 이동을 권하게 하는게 대부분이다.

일반적으로 서버군에 따라 각각 물리적으로 분리된 데이터베이스를 사용하게 된다. 때문에 서버군을 이동하게 되면 데이터베이스가 바뀌기 때문에 개발사에 따라 기존의 캐릭터를 그대로 옮겨 갈 수도 있거나 아니면 새로 만들어야 하는 문제가 생기곤 한다. 개발사에서는 새로 오픈하게 되는 서버군에서 캐릭터들의 형평성을 위해 특별한 이유가 없는한 이전에 사용하던 캐릭터를 다른 서버군으로 옮기지 못하게 한다. 대부분의 온라인 게임이 이러한 구조를 택하고 있고, 하나의 캐릭터가 서로 다른 서버군을 옮겨 다니며 게임을 할 수 있게 만든다는 것은 분명 쉬운 일이 아니다.



질문 : 통합된 월드의 게임 서버를 만드는데 가장 문제가 되는 것은 무엇인가?

: 첫번째는 통합된 월드내 수많은 유저의 정보를 실시간으로 저장할 수 있는 데이터베이스가 가장 문제가 된다. 서버군의 유저수를 통제하는 것도 데이터베이스의 문제가 주요인이다. 그 이유는 데이터베이스가 실시간으로 동시에 처리할 수 있는 능력은 시스템에 따라 한계치가 있기 때문이다. 두번째는 데이터베이스의 부하를 분산하기 위해 replication 기능을 생각해 볼 수도 있다. 하지만 replication 기능도 상황에 따라 한쪽 데이터베이스에서 오류가 발생할 경우 처리 문제는 상당히 까다롭다. 실시간으로 오류 발생 즉시 다른 한쪽으로 데이터베이스 커넥션을 바꾸어야 하는데 이또한 임시적인 방책이지 해결책은 될 수가 없다. 부하가 심해 오류가 발생되었다고 오류가 없는 데이터베이스로 커넥션을 옮긴다면 한쪽으로 부하가 집중되어 역시 오류가 발생할 문제가 다분해 지기 때문이다. 세번째는 실시간으로 부하를 분산해야 하는 문제가 있다. 갑자기 하나의 지역에 많은 유저가 몰리게 된다면 시스템의 한계에 의해 서버의 처리 속도가 현저하게 느려지거나 심할경우 OS 가 다운이 될 수 있기 때문이다. 부하를 실시간으로 분산시킬 수 있는 것은 상당히 까다로운 문제이다.



replication란? 데이터베이스의 복제 기능이다. 똑같은 정보를 가지고 있는데이터베이스들끼리 연결되어 한쪽 데이터베이스에 정보가 입력된다면 입력된 데이터를다른 데이터베이스에도 똑같이 입력되게 하는 데이터베이스 기능이다.

필자의 경우 같은 지역을 여러대의 맵서버가 관리하는 분산 구조를 간단하게 테스트 해본 적이 있다. 구조는 동기화 서버( 1대 ) + 게임 서버( 여러대 ) 의 구조이다.

Article/Dispersion_struct.gif
<그림 4> 게임 서버의 분산 구조

동기화 전문 서버를 한대 두고 그에 여러대의 동일한 맵서버가 연결되어 부하를 분산시켜주는 구조이다. 동기화 서버와 맵 서버간에는 UDP 를 이용하여 데이터를 송수신 한다. 예를 들어 동기화 서버에 2 대의 게임서버 1, 2 를 붙이게 된다면 유저들은 게임 서버 앞단에 있는 로드밸런싱 서버에 의해 적은수의 유저가 있는 게임 서버를 알게하여 게임 서버 1, 2 에 분산되어 접속하고 게임을 하게 되지만 같은 섹터에 있는 캐릭터는 동기화 서버에 의해 동기화가 되는 구조이다.

물리적으로는 분리되어 있는 게임서버 1, 2 이지만 동기화 서버에 의해 논리적으로는 같은 서버에 존재하게 되는 것이다. 동기화 서버는 오직 캐릭터들의 동기화 작업만 수행하기 때문에 디스크 I/O 가 없어 부하를 적게 차지하여 여러대의 동일한 공간의 게임 서버를 동기화 시킬수 있는 구조이기 때문에 많은 유저들을 수용할 수 있다.


서버간의 통신 #


이전에 필자가 구현 했던 MMORPG 의 서버군의 구성은 다음과 같다. <그림 5> 를 보면서 서버간의 통신에 대해 이야기 해보자.

Article/Server_Group.gif
<그림 5> 서버군

<그림 5> 의 서버군은 패치 + 로그인 + 로비 + 맵 + 관리 서버의 구조로 되어 있다. 서버간의 통신은 UDP 프로토콜을 이용하며 관리 서버를 중간에 두어 월드의 모든 접속자 리스트를 가지고 접속자 관리, 전체 메세지 전송, 타 서버에 있는 케릭터에 귀속말 전달 등의 일을 담당한다. 유저가 인증에 성공을 하게되면 최초 인증 서버에서 관리 서버로 유저의 기본 데이터를 송신하여 유저의 연결 리스트에 추가를 하게 된다. 유저가 월드를 선택하고 캐릭터를 선택하여 게임 서버에 접속을 하게 되면 게임 서버에서 관리 서버로 관련 정보를 송신한다. 관리 서버에서는 데이터를 수신하여 연결리스트의 해당 유저 노드를 잘라내어 월드 트리의 해당 서버 브렌치에 노드를 추가하게 된다.

각 게임 서버들은 2 개의 네트워크 인터페이스 ( 랜카드 ) 를 사용하여 각각 외부/내부 네트워크 전용으로 사용하였다. 특히 데이터베이스의 경우 외부 네트워크와 차단하여 혹시 있을 수 있는 해킹에 대비하였다. 내부 네트워크와 외부 네트워크로 구분하기 위해 각각의 네트워크 인터페이스 카드 ( 랜카드 ) 하나 ( 랜카드1 ) 에는 공인 IP 를 또 다른 하나 ( 랜카드2 ) 에는 사설 IP 를 부여 하였다. 사설 IP 는 B 클래스 172.16.0.0 - 172.31.255.255 영역을 사용하였다. B 클래스를 쓴 이유는 네트워크당 65000 개의 호스트를 수용하기 때문에 서버가 많이 늘어나도 아이피가 부족할 일이 없기 때문이다. <표 1> 는 내부 네트워크에서 사용하는 클래스의 IP 대역과 네트워크당 수용 가능한 호스트의 수이다.

클래스 IP 대역 네트워크당 수용 호스트 수
A Class10.0.0.0 ~ 10.255.255.255 16777214 개
B Class172.16.0.0 ~ 172.31.255.255 65534 개
C Class192.168.0.0 ~ 192.168.255.255254 개
<표 1> 클래스 대역폭 및 수용 호스트수

각 서버들의 정보는 데이터베이스에 저장되어 있기 때문에 처음 서버가 구동될 때에는 전체 서버군에 있는 서버들의 정보를 적재 ( load ) 시킨다. 적재된 서버의 정보는 서버 인덱스와 내부 아이피 정보인데, 각각의 서버들은 다른 서버와의 통신을 위해 서버 정보들을 사용한다. 통신이 필요한 서버에 메세지를 송신하고 수신받은 서버에서는 메세지에 따른 처리를 한 후에 다시 응답 메세지를 보내주면 하나의 통신이 완료되는 것이다.

서버간에 전송되는 메세지는 주로 캐릭터가 게임 서버를 이동할 때 사용되는 패킷과 귀속말 패킷이 주로 사용된다. 유저가 게임 서버를 이동할 때에는 캐릭터가 위치하고 있는 포탈 인덱스에서 이동하려는 서버의 인덱스를 알아내어 클라이언트에게는 이동하려는 서버의 아이피, 접속 포트 번호, 인증 키 등을 전송하고, 캐릭터가 현재 위치하고 있는 서버에서는 이동하려는 서버로 인증키 등을 전송한다. 클라이언트에서는 현재 서버로부터 받은 아이피와 포트로 새로운 서버로 접속을 하고 인증키를 통해 인증을 받게 된다. 서버간 통신은 랜카드2 를 통해서만 송/수신 ( 서버간의 패킷은 사설 아이피로 수신된 패킷만 인정하고 공인 아이피로 온 패킷은 무시 ) 하기 때문에 혹시 있을 수 있는 사용자의 해킹을 방지한다. <표 2> 은 IP address 별 사용 용도와 특징을 정리한 내용이다.

공인 IP 사설 IP
차이점클라이언트와의 통신서버간의 통신
서버간의 통신 사용불가클라이언트간 통신 사용불가
공통점서버간의 통신에서 네트워크 대역폭 확보 및 물리적인 보안
<표 2> IP address 사용

외부로 부터의 보안을 위해 서버는 TCPWRAPPER 를 사용하여 관리자 아이피 외의 접근을 막았다. 게임 산업이 발전함에 따라 게임 서버의 보안 문제가 이슈가 된지는 오래이며 유명 게임 서버들의 경우 해커의 공격 목표가 되기도 한다. 해킹에 의해 소스나 데이터베이스가 유출되기도 하기 때문에 개발사들은 보안에 만전을 기해야 한다. 시스템의 해킹은 자칫 큰 문제가 되어 게임의 흥망에도 큰 영향을 미칠수 있기 때문에 중요한 문제이다.

TCPWRAPPER란? Wietse Vanema 에 의해 제작된 TCPwapper 는 호스트 레벨에서 특정프로토콜과 포트, 네트워크 IP 에 따른 접속허가를 내줄 것인지 거부할 것인지 결정하는packet dropper 이라고 볼 수 있다.

스마트그리드 개념 : form 스마트그리드협회

http://www.k-smartgrid.org/


전력시스템과 IT 기술의 융합,

스마트 그리드 요약보고서....

전력시스템을 익히자!!!!!!

1264251649_스마트 그리드 - 요약보고서.pdf

저랩의 우울함.....



'사이버탐험기' 카테고리의 다른 글

SL 탐험기 2010.01.24 세컨드라이프라니...  (1) 2010.01.24
저랩의 와우이야기1  (0) 2010.01.23
넥슨별 레벨업!!!!  (0) 2010.01.17
넥슨별 생활이란....  (0) 2010.01.10
꿈의 별! 넥슨별!  (0) 2010.01.03

+ Recent posts