'Develop'에 해당되는 글 10건

  1. 2013.04.08 Small TCP/IP Hello Client Software with VB 6.0
  2. 2013.04.08 Small TCP/IP Hello server with VB 6.0
  3. 2012.07.18 안드로이드(android)에서 java 의 HttpClient 4.0 클래스를 이용한 네트웍 프로그램 구현
  4. 2012.04.25 이클립스 속도 올리기
  5. 2012.04.19 JAVA 온라인 강좌
  6. 2012.04.12 20120412 report(JAVA)
  7. 2012.04.10 우편번호 변환
  8. 2012.03.28 SE & NE 에서 프로그래머로 변신
  9. 2012.01.26 이클립스 한글패치
  10. 2012.01.11 이클립스에서 안드로이드 설정

Small TCP/IP Hello Client Software with VB 6.0

|

This article is second part of a two-part article for 
programmers who want to start writing socket programs with 
VB.

In previous part of this article we saw how we can write a 
simple hello server in VB. We used a socket object that 
comes with VB for this purpose. Mswnsock.ocx is a very 
stable socket object that we used in our program. 

This example uses Winsock component again. You will need a 
form with a command button (command1), a socket component 
(winsock1) and a list box (list1) in this example.

We will need to do the following steps to have our hello 
client connect to our server and communicate with it.

1- This time we don't need to bind anything.

2- when we press connect key (command1) socket starts 
connecting to a server via TCP/IP network. Connect function 
needs two parameters before it can connect to a server. 

IP address specifies the host that server is running on it. 
As we want the client to connect server program running on 
our own server we use loop back address that points to our 
computer. Loop back address is �127.0.0.1�. You can use 
address of any other host instead of this. 

Second parameter is TCP port. As you know can assign a port 
number between 1 and above 65000 to each clinet/server 
application. 

This is TCP channel we use to avoid communication conflicts 
between different programs that communicate between two 
hosts. We chose an optional port number of 1024.


3- When a client socket opens a connection to server program,
a connect event is triggered on client program. When we 
receive this event we start sending data to server and 
also simultaneously show it in listbox1. Message sent to 
server is "hi!"

4- After server has finished receiving sent data, it sends 
back answer data that is 멻ello� string. It will close 
connection after it has sent its data. So closing 
connections is done by server side. 

5- If any error occurs on socket an 'onerror' event is 
triggered. In this case we will display an error message.

And now program source:

Private Sub Command1_Click()
If Winsock1.State <> sckClosed Then
Winsock1.Close
End If
Winsock1.Connect "127.0.0.1", 1024
End Sub

Private Sub Winsock1_Connect()
Winsock1.SendData "Hi!" + vbCrLf
List1.AddItem "Sent to Server: Hi!"
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData a$, vbString
List1.AddItem "Received from server: " + a$
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, 
Description As String, ByVal Scode As Long, 
ByVal Source As String, ByVal HelpFile As String, 
ByVal HelpContext As Long, CancelDisplay As Boolean)

MsgBox "Error in socket : " + Description, vbOKOnly

End Sub

If you need codes for this article you can visit our site 
and go to ezine page. There you will find a link to zip 
source files.

http://op.htmsoft.com/ezines.html

 

 

http://op.htmsoft.com/articles/Articlea2-1-2.html


 

'Develop > VB6' 카테고리의 다른 글

Small TCP/IP Hello server with VB 6.0  (0) 2013.04.08
And

Small TCP/IP Hello server with VB 6.0

|

This article is first part of a two part article for people 
who want to start writing socket programming with VB.

This example uses an ocx component that comes with VB. You 
will need a from with a command button (command1), a socket 
component (winsock1) and a listbox (list1).

We will need to do the following steps to have our hello 
server running.

1- We must bind TCP/IP socket to port 1024 when form loads.

2- When we press Listen Key (command1) socket starts 
   listening port 1024. In this way program will be able to 
   accept connections. Listening socket is usually used for 
   just receiving TCP/IP connections. It will also queue 
   them until our program is free to serve them. We will 
   usually need another socket to service connections that
   has been queued. However as we want to create a small 
   server we will use a single socket for both listening 
   and communication with client programs.

3- When a socket on a remote program opens a connection to 
   our program, a Connection request event is triggered and 
   ConnectionRequest subroutine is automatically called.
   In this subroutine we can accept the connection.

4- Now that everything is prepared, whenever an accepted 
   socket tries to send us data another event called 
   DataArrival will be triggered. When we receive this event 
   we first read data that is sent to us and show it in a 
   listbox and then send a 'hello' string back to the client 
   program connected to us. This is why we call this server 
   a 'hello' server. 

5- After sending data, server has no reason to keep 
   connection so it must close the connection.
   When sending data is finished, a SendComplete event is 
   triggered. As we want to accept more connections we close 
   socket and then call listen function again to be ready 
   for accepting other incoming connections.

6- If any error occurs on socket an 'onerror' event is 
   triggered. In this case we will display an error message.

And now program source:

Private Sub Command1_Click()
  Winsock1.Listen
End Sub

Private Sub Form_Load()
  Winsock1.Bind 1024
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
  If Winsock1.State <> sckClosed Then Winsock1.Close
  'Load Winsock1(newInstanceIndex)
  Winsock1.Accept requestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
  Winsock1.GetData a$, vbString
  'received data is in a$ , you can use it
  List1.AddItem ("Received : " + a$)
  Winsock1.SendData "hello" + vbCrLf
  'The string 'hello' is sent in answer to client request
  List1.AddItem ("Sent : Hello")
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, 
            Description As String, ByVal Scode As Long,
            ByVal Source As String, ByVal HelpFile As String,
            ByVal HelpContext As Long,
            CancelDisplay As Boolean)

  MsgBox "Error in Socket" + Description, vbOKOnly, "Error"
End Sub

Private Sub Winsock1_SendComplete()
  Winsock1.Close
  Winsock1.Listen
End Sub


7- Server written in this article can serve one connection 
   at a time. If you want you can use more connections by 
   loading new sockets for each incoming connection.

In next part of this article we will write a client side 
program for this server. 

Client program will connect server program over network and 
will receive 'hello' string and then connection will be 
closed by server program. You can test this program by 
connecting to port 1024 using a telnet program. Whatever you
send to it, server will answer with a 'hello'.

If you need codes for this article you can visit our site 
and go to ezine page. There you will find a link to zipped 
source files.

 

'Develop > VB6' 카테고리의 다른 글

Small TCP/IP Hello Client Software with VB 6.0  (0) 2013.04.08
And

안드로이드(android)에서 java 의 HttpClient 4.0 클래스를 이용한 네트웍 프로그램 구현

|

자료출처 : http://mainia.tistory.com/568


안드로이드(android)에서 java HttpClient 4.0 클래스를 이용한 네트웍 프로그램 구현

개발환경 : JDK 1.5, eclipse-galileo, Google API 7(android API 2.1), window XP

org.apache.http.client.HttpClient 클래스는 안드로이드 뿐만 아니라 여러가지로

쓸만한데가 많아서 몇가지 예제를 정리 하였다. 나 같은 경우에는 안드로이드에서

서버와 통신하며 데이터를 받아올 때 사용한다. 안드로이드 API 내부에 HttpCliet

가 포함되어있기 때문이다.

(1) HttpClient 를 이용하여 POST 방식으로 멀티파일 업로드 구현

이 예제는 java application 으로 만든것이다. 서버에 WAS 가 돌고 있다면 멀티 파일 업로드가

가능하다. 로컬상에 web application 하나 구현해 놓고 테스트 해보면 될것이다.


01import java.io.File;
02import org.apache.http.HttpEntity;
03import org.apache.http.HttpResponse;
04import org.apache.http.HttpVersion;
05import org.apache.http.client.HttpClient;
06import org.apache.http.client.methods.HttpPost;
07import org.apache.http.entity.mime.MultipartEntity;
08import org.apache.http.entity.mime.content.ContentBody;
09import org.apache.http.entity.mime.content.FileBody;
10import org.apache.http.impl.client.DefaultHttpClient;
11import org.apache.http.params.CoreProtocolPNames;
12import org.apache.http.util.EntityUtils;
13
14
15public class PostFile {
16 public static void main(String[] args) throws Exception {
17 HttpClient httpclient = new DefaultHttpClient();
18 httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
19
20 HttpPost httppost = new HttpPost("http://localhost:9001/upload.do");
21 File file = new File("c:/TRASH/zaba_1.jpg");
22
23 MultipartEntity mpEntity = new MultipartEntity();
24 ContentBody cbFile = new FileBody(file, "image/jpeg");
25 mpEntity.addPart("userfile", cbFile);
26
27
28 httppost.setEntity(mpEntity);
29 System.out.println("executing request " + httppost.getRequestLine());
30 HttpResponse response = httpclient.execute(httppost);
31 HttpEntity resEntity = response.getEntity();
32
33 System.out.println(response.getStatusLine());
34 if (resEntity != null) {
35 System.out.println(EntityUtils.toString(resEntity));
36 }
37 if (resEntity != null) {
38 resEntity.consumeContent();
39 }
40
41 httpclient.getConnectionManager().shutdown();
42 }
43}

(2) HttpClient 를 이용하여 일반 데이터 전송/ 받기

이 예제는 파일이 아닌 일반 text 데이터를 BasicNameValuePair 담아서 전송한다. 하나하나 담은

데이터는 다시 ArrayList 클래스에 넣고 UrlEncodedFormEntity 클래스로 UTF-8 로 인코딩한다.

서버에서 작업된 내용을 받을때는 ISO-8859-1 디코더해서 BufferedReader 로 읽어 들인다

그리고 마지막에 getConnectionManager().shutdown() ; 해준다.

01InputStream is = null;
02String totalMessage = "";
04HttpClient httpclient = new DefaultHttpClient();
05try {
06 /** 연결 타입아웃내에 연결되는지 테스트, 5초 이내에 되지 않는다면 에러 */
07 String id = "id";
08 String pwd = "password";
09
10 ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>();
11 nameValuePairs.add(new BasicNameValuePair("ID", id));
12 nameValuePairs.add(new BasicNameValuePair("PWD", pwd));
13
14 /** 네트웍 연결해서 데이타 받아오기 */
15 String result = "";
16 HttpParams params = httpclient.getParams();
17 HttpConnectionParams.setConnectionTimeout(params, 5000);
18 HttpConnectionParams.setSoTimeout(params, 5000);
19
20 HttpPost httppost = new HttpPost(url);
21 UrlEncodedFormEntity entityRequest =
22new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
23 httppost.setEntity(entityRequest);
24
25 HttpResponse response = httpclient.execute(httppost);
26 HttpEntity entityResponse = response.getEntity();
27 is = entityResponse.getContent();
28
29 /** convert response to string */
30 BufferedReader reader = new BufferedReader(new InputStreamReader(
31 is, "iso-8859-1"), 8);
32 StringBuilder sb = new StringBuilder();
33 String line = null;
34 while ((line = reader.readLine()) != null) {
35 sb.append(line).append("\n");
36 }
37 is.close();
38 result = sb.toString();
39
40} catch (IOException e) {
41 e.printStackTrace();
42} chatch (Exception e)
43 e.printStackTrace();
44
45} finally {
46 httpclient.getConnectionManager().shutdown();
47}
48</namevaluepair></namevaluepair>

위의 내용은 아이디/패스를 서버에 전달하고 그 결과값을 받기 위해서 만들었던 것이다.

서버나 네트웍 상태가 안좋아서 데이터를 받아 올수 없을 때 무작정 기다릴수 없으므로

5초로 셋팅해주었다. 5초 이상 반응이 없으면 exception 을 던지게 된다.

이것으로 안드로이드에서 실시간 서비스정보구현을 위한 기본적인 코딩은 된것이다.

추가로 구현해야될 사항은 네트웍 연결부분을 별도의 쓰레드로 돌려야 되고 , 데이터를

받고 전달해줄 서버를 구현해야한다. 그리고 JSON 프로토콜을 사용할것이 때문에

JSON 파싱을 위한 구현을 해야한다

'Develop > Android' 카테고리의 다른 글

우편번호 변환  (0) 2012.04.10
And

이클립스 속도 올리기

|

1. 이클립스 옵션 조정

우선 이클립스 폴더안에 있는 eclipse.ini에 다음을 추가 하거나 수정해 줍니다.

-Xverify:none
-XX:+UseParallelGC
-Xms256M
-Xmx512M


-Xverfify :

초기 시동시 verfify체크를 하지 않습니다. 당연히 시동이 빨라 집니다. 플러그인아 features에 문제가 발생 할 수 있습니다. 플러그인아 변경 사항이 있을 경우에는 이걸 키고 시동하시고, 별 문제 없으면 추가해서 사용하세요.
-XX:+UseParallelGC :
Parallel Collector를 사용 하도록 합니다. 패러럴로 모아 준다니.. 빨라지겠죠.. 체감 속도가 올라 갑니다. 다중 프로세서를 사용하시는 분들은 필수.
-Xms256M
이클리스가 시작시 잡는 메모리(256메가 바이트)
-Xmx512M
이클리스가 사용하는 최대 메모리(512메가 바이트). 메모리가 어느 정도 되신다고 생각 하시면, 늘려 주셔도 됩니다.



2. 중간중간 메모리를 정리해 주자


Window > Perference > General에 보면 Show heap status라는 옵션이 있습니다. 이걸 켜 주시면, 화면 오른쪽 하단에 아래와 같은 아이콘이 생깁니다.
사용하다가, 메모리가 많이 올라 갔다 싶거나, 느려졌네 싶을때 마다, 옆에 쓰레기통 아이콘을 눌러 주세요. 메모리가 확 줄어 듭니다. 그러면 좀 더 쾌적하게 작업을 하 실 수 있을 겁니다.

추가로 메모리는 좀 들긴 하지만 자동 가비지 컬랙션 해주는 플러그인을 설치 하셔도 됩니다.




3. 사용하지 않는 검사를 없애 준다.

필요 이상으로 많은 검사를 많이 해서 느려지는 경우도 많습니다. HTML이나 그외 등등의 검사도 거기에 포함되죠, 딱 필요한 검사만 하도록 합니다.
Window > Perferences > Validation에서 자기가 사용하는 옵션을 켜 줍니다. 저같은 경우에는 PHP를 요즘 사용하고 있어서.. PHP만 켜 줬습니다.

그리고, 영어 스펠링 검사입니다. 영어 단어를 잘 모르지만, 느려지는건 못 참아서.. 그냥.. 꺼 줬습니다.
Window > Prereces > General > Editors > Spellings에서 Enable spell checking을 과감하게 꺼 줍니다.



5. 잘 안 쓰는 기능 끄기 및 사용습관 바꾸기.


코딩하는 공간에서 잘 사용하지 않거나, 있는둥 마는둥 하는 기능을 꺼 줍니다.

Automatic folding 끄기
코드 옆에 더하기 표시 나와서, 코드를 펼쳤다.. 닫았다 하는 기능입니다. 눈에도 안 띄고 전 잘 안 쓰는 기능이라서 꺼 버립니다.
Window->Preferences->Java(또는 사용언어)->Editor->Folding 모든 옵션을 해제(disable) 합니다.옵션을 모두 해제(disable)한다.

Automatic Code Insight 끄기
Window->Preferences->Java(또는 해당언어)->Editor->Code Assist 에서 Enable auto activation 항목을 해제(disable)합니다. 자동으로 동작하는 code assist 기능은 꺼지지만, ctrl+space러 여전히 code assist를 사용할 수 있습니다. 손이 좀 불편하면 이클립스가 빨라집니다 -_-;;

사용하지 않는 플러그인 삭제 하기
이클립스를 패키지로 설치 하도 보면, 사용하지 않는 기능도 많이 들어 가게 됩니다. 그리고 이것저것 설치하기도 하고요. 그 중에서 사용하지 않는 플러그인은 삭제해 주세요.

사용하지 않는 프로젝트 닫아주기
현재 작업과 관련없는 프로젝트를 닫아 주세요. 이클립스가 접근하는 파일의 갯수를 줄여 줍니다.

사용하지 않는 파일은 닫아주기
작업하다가 사용하지 않는 창은 닫아주세요. 메모리가 절약됩니다. 이클립스를 종료시 편집하던 문서를 모두 닫고 종료하는건 다음에 이클립스를 띄울때 좀 더 가볍게 띄울 수 있습니다. 그리고 Window->Preferences->General->Editors에서 Close editors automatically를 켜주세요. 그럼 아래 설정된 숫자만큼만 문서가 열립니다. 그 이상의 문서는 자동으로 닫아집니다. 이렇게 사용하면, 무심결에 많이 열린 파일이 적어집니다. 메모리도 절약 되고요.. ^^*

사용하지 않는 플러그인을 start list에서 제외하기
Window > Preferences > General > Startup and Shutdown에서, 불필요한 플러그인을 startup list에서 제외합니다. 이렇게 하면 이클립스 실행시 좀 더 가볍게 실행 할 수 있습니다.



6. 그래도 느리다.


좀 더 처절하게 가 보겠습니다.

이클립스가 설치된 폴더에 바이러스를 검사를 꺼보세요.
백신마다 보면, 예외사항이 있을 겁니다. 거기서 이클립스가 설치 된 폴더를 예외에 넣어 주세요. 백신을 끄고 사용하면 더 좋지만, 그것 까지는 좀 그렇다면, 이 정도만 해 주세요.

작업하는 파일들과 이클립스 프로그램을 작은 파티션을 만들어서 관리해 주세요.
헤더의 움직임을 최소화 해주고 빨라집니다. 하드디스크에서 디스크 조각모음하는것 보다 훨씬 좋습니다.





7. 그래도 느려서 못 해 먹겠다.

마지막으로 그래도 정말 안 되겠다..
어쩔수 없습니다. 호주머니를 여실 수 밖에,
메모리를 늘리고 CPU를 최신으로 올리고, OS를 64bit로 올려 주세요.
위에 껄 뭐 하려고 했나 싶을 정도로 빨라집니다. -_-;;;

'Develop' 카테고리의 다른 글

SE & NE 에서 프로그래머로 변신  (0) 2012.03.28
And

JAVA 온라인 강좌

|

'Develop > Java' 카테고리의 다른 글

20120412 report(JAVA)  (0) 2012.04.12
이클립스 한글패치  (0) 2012.01.26
이클립스에서 안드로이드 설정  (0) 2012.01.11
And

20120412 report(JAVA)

|

/*
 * Test / Ch10Test.java
 * 프로그램 설명 :
 * 작성 일자   : 2012. 4. 12.
 * 작성자   :
*/
package Test;

public class Ch10Test {
 public static void main(String[] args) {
  Sungjuk sj = new Sungjuk();
  sj.start();
 }
}
*****************************************************************************

/*
 * Test / Sungjuk.java
 * 프로그램 설명 :
 * 작성 일자   : 2012. 4. 12.
 * 작성자   :
*/
package Test;

import java.util.Scanner;

public class Sungjuk {
 Scanner sc;
 
 public Sungjuk() {
  sc = new Scanner(System.in);
 }
 
 public void menuDsp(){
  System.out.println("1. 성적 출력");
  System.out.println("2. 성적 입력");
  System.out.println("3. 성적 삭제");
  System.out.println("4. 종료");
 }
 
 public void start() {
  boolean re = true;
  while(re){
   menuDsp();
   System.out.print("번호 입력 ");
   int num = sc.nextInt();
   switch(num){
    case 1:System.out.println("성적 출력");
    break;
    case 2:System.out.println("성적 입력");
    break;
    case 3:System.out.println("성적 삭제");
    break;
    default:
     re = false;
    break;
   }
  }

 }
}

 

'Develop > Java' 카테고리의 다른 글

JAVA 온라인 강좌  (0) 2012.04.19
이클립스 한글패치  (0) 2012.01.26
이클립스에서 안드로이드 설정  (0) 2012.01.11
And

우편번호 변환

|

우편번호 검색

API or 파싱

자료출처 : http://blog.naver.com/yell301/130094111018

And

SE & NE 에서 프로그래머로 변신

|
1996년부터 2010년
결혼을 하기 전까지....
오로지 컴퓨터만 해왔다.

시스템 엔지니어로써 이런 저런 프로젝트를 해오면서 느끼는 애환과 답답함은 항상 존재한다.

엔지니어로써 한계 끝없는 긴장과 대기..
결국 잃어버린 건강

결혼과 동시에 사직을 하고 초야에 살아가고 있었으나 살아야하기에 그리고 하고 싶은 일이나 해야할 일을 찾아야 하기에

내가 원하는걸 내가 만들자고 하기에 시스템 엔지니어에서 개발자로 변신하고자 환골탈태를 준비중이다.

주어 들은 많기에 오히려 방해가 되는 부분이 많다 머리를 초기화하고 대학 다닐 때 신입생의 설레임으로 임하고자 한다.

을 회사에서 소방수 역활만 해오다
어린 친구들과 여럿이서 공부하는 것도 좋고 물을수 있는 사람이 있어 더욱 기분이 좋은 나날 ^^

아자아자 기운내자!!!

iPhone 에서 작성된 글입니다.

'Develop' 카테고리의 다른 글

이클립스 속도 올리기  (0) 2012.04.25
And

이클립스 한글패치

|

'Develop > Java' 카테고리의 다른 글

JAVA 온라인 강좌  (0) 2012.04.19
20120412 report(JAVA)  (0) 2012.04.12
이클립스에서 안드로이드 설정  (0) 2012.01.11
And

이클립스에서 안드로이드 설정

|
이게 실제 책이랑 온라인에 나타나는 부분이랑 많이 다름
이유 찾는중
섬세하게 다룰 예정
모가 되야 개발을 하지 개늠들
http://javai.tistory.com/entry/이클립스-안드로이드-셋팅2

'Develop > Java' 카테고리의 다른 글

JAVA 온라인 강좌  (0) 2012.04.19
20120412 report(JAVA)  (0) 2012.04.12
이클립스 한글패치  (0) 2012.01.26
And
prev | 1 | next