==========================================================================================

C#

==========================================================================================

<C#>



=클래스 다이아그램





=배포 버전 software (installsheld- 유료)




-1. 웹상 다운로드 (ex - 한게임)

-2. cd...




=설치파일

















=싱글채팅

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net; //IP Address
using System.Net.Sockets; // TcpListener 클래스 사용
using System.Threading; // 스레드 클래스 사용
using System.IO; // 파일 클래스 사용
using Microsoft.Win32; // 레지스트리 클래스 사용
using System.Runtime.InteropServices; // 폼 깜박임 구현

namespace attribute
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }
        
private TcpListener Server; // TCP 네트워크 클라이언트에서 연결 수신
        private TcpClient SerClient, client; // TCP 네트워크 서비스에대한 클라이언트 연결 제공
        private NetworkStream myStream; // 네트워크 스트림
        private StreamReader myRead; // 스트림 읽기
        private StreamWriter myWrite; // 스트림 쓰기
        private Boolean Start = false// 서버시작
        private Boolean ClientCon = false// 클라이언트 시작
        private int myPort; //포트
        private string myName; //별칭
        private Thread myReader, myServer; //스레드
        private Boolean TextChange = false// 입력 컨트롤의 데이터 입력 체크

        private RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"true); 

                                                                                                                    // 레지스트리 쓰기, 읽기

        private delegate void AddTextDelegate(string strText); // 델리게이트 개체 생성
        private AddTextDelegate AddText = null; // 델리게이트 개체 생성

        [DllImport("User32.dll")]
        
private static extern bool FlashWindow(IntPtr hwnd, bool bInvert);

        
private void 설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
this.설정ToolStripMenuItem.Enabled = false;
            
this.plOption.Visible = true;
            
this.txtId.Focus();
            
this.txtId.Text = (string)key.GetValue("Message_name"); // 별칭 입력
            this.txtPort.Text = (string)key.GetValue("Message_port"); // 포트 입력
        }

        
private void 닫기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
this.Close(); // 폼 닫기
        }

        
private void btnSave_Click(object sender, EventArgs e)
        {
            
if(this.cbServer.Checked == true// 서버모드 실행
            {
                ControlCheck();
            }
            
else // 클라이언트 실행
            {
                
if(this.txtIp.Text == "")
                {
                    
this.txtIp.Focus();
                }
                
else
                {
                    ControlCheck();
                }
            }
        }

        
private void ControlCheck()
        {
            
try
            {
                var name 
= this.txtId.Text;
                var port 
= this.txtPort.Text;
                key.SetValue(
"Message_name", name);
                key.SetValue(
"Message_port", port);
                
this.plOption.Visible = false;
                
this.설정ToolStripMenuItem.Enabled = true;
                
this.tsbtnConn.Enabled = true;
            }
            
catch
            {
                MessageBox.Show(
"설정이 저장되지 않았습니다.""에러", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
private void btnClose_Click(object sender, EventArgs e)
        {
            
this.설정ToolStripMenuItem.Enabled = true// 설정메뉴 활성화
            this.plOption.Visible = false// 입력창 닫기
            this.txtMessage.Focus();
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            
if((string)key.GetValue("Message_name")=="")
            {
                
this.myName = this.txtId.Text;
                
this.myPort = Convert.ToInt32(this.txtPort.Text);
            }
            
else
            {
                
try
                {
                    
this.myName = (string)key.GetValue("Message_name");
                    
this.myPort = Convert.ToInt32(key.GetValue("Message_port"));
                }
                
catch
                {
                    
this.myName = this.txtId.Text;
                    
this.myPort = Convert.ToInt32(this.txtPort.Text);
                }
            }
        }

        
private void tsbtnConn_Click(object sender, EventArgs e)
        {
            AddText 
= new AddTextDelegate(MessageView);
            
if(this.cbServer.Checked == true)
            {
                var addr 
= new IPAddress(0);
                
try
                {
                    
this.myName = (string)key.GetValue("Message_name");
                    
this.myPort = Convert.ToInt32(key.GetValue("Message_port"));
                }
                
catch
                {
                    
this.myName = this.txtId.Text;
                    
this.myPort = Convert.ToInt32(this.txtPort.Text);
                }

                
if(!(this.Start))
                {
                    
try
                    {
                        Server 
= new TcpListener(addr, this.myPort);
                        Server.Start();

                        
this.Start = true;
                        
this.txtMessage.Enabled = true;
                        
this.btnSend.Enabled = true;
                        
this.txtMessage.Focus();
                        
this.tsbtnDisconn.Enabled = true;
                        
this.tsbtnConn.Enabled = false;
                        
this.cbServer.Enabled = false;

                        myServer 
= new Thread(ServerStart);
                        myServer.Start();

                        
this.설정ToolStripMenuItem.Enabled = false;
                    }
                    
catch
                    {
                        Invoke(AddText, 
"서버를 실행 할 수 없습니다.");
                    }
                }
                
else
                {
                    ServerStop(); 
// ServerStop()함수 호출
                }
            }
            
else
            {
                
if(!(this.ClientCon))
                {
                    
this.myName = (string)key.GetValue("Message_name"); // 별칭 설정
                    this.myPort = Convert.ToInt32(key.GetValue("Message_port")); // 서버측 포트 설정
                    ClientConnection(); // ClientConnection()함수 호출
                }
                
else
                {
                    
this.txtMessage.Enabled = false;
                    
this.btnSend.Enabled = false;
                    Disconnection(); 
// 함수 호출
                }
            }
        }

        
private void tsbtnDisconn_Click(object sender, EventArgs e)
        {
            
try
            {
                
if(this.cbServer.Checked)
                {
                    
if(this.SerClient.Connected)
                    {
                        var dt 
= Convert.ToString(DateTime.Now);
                        myWrite.WriteLine(
this.myName + "&" + "채팅 APP가 종료되었습니다." + "&" + dt);
                        myWrite.Flush();
                    }
                }
                
else
                {
                    
if(this.client.Connected)
                    {
                        var dt 
= Convert.ToString(DateTime.Now);
                        myWrite.WriteLine(
this.myName + "&" + "채팅 APP가 종료되었습니다." + "&" + dt);
                        myWrite.Flush();
                    }
                }
            }
            
catch
            {

            }
            ServerStop();
            
this.설정ToolStripMenuItem.Enabled = true;
        }

        
private void ServerStart()
        {
            Invoke(AddText, 
"서버 실행 : 챗 상대의 접속을 기다립니다...");
            
while(Start)
            {
                
try
                {
                    SerClient 
= Server.AcceptTcpClient();
                    Invoke(AddText, 
"챗 상대 접속..");
                    myStream 
= SerClient.GetStream();

                    myRead 
= new StreamReader(myStream);
                    myWrite 
= new StreamWriter(myStream);
                    
this.ClientCon = true;
                    myReader 
= new Thread(Recieve);
                    myReader.Start();
                }
                
catch
                {

                }
            }
        }

        
private void ServerStop()
        {
            
this.Start = false;
            
this.txtMessage.Enabled = false;
            
this.txtMessage.Clear();
            
this.btnSend.Enabled = false;
            
this.tsbtnConn.Enabled = true;
            
this.tsbtnDisconn.Enabled = false;
            
this.cbServer.Enabled = true;
            
this.ClientCon = false;
        }

        
private void ClientConnection()
        {
            
try
            {
                client 
= new TcpClient(this.txtIp.Text, this.myPort);
                Invoke(AddText, 
"서버에 접속 했습니다.");
                myStream 
= client.GetStream();

                myRead 
= new StreamReader(myStream);
                myWrite 
= new StreamWriter(myStream);
                
this.ClientCon = true;
                
this.tsbtnConn.Enabled = false;
                
this.tsbtnDisconn.Enabled = true;
                
this.txtMessage.Enabled = true;
                
this.btnSend.Enabled = true;
                
this.txtMessage.Focus();

                myReader 
= new Thread(Recieve);
                myReader.Start();

            }
            
catch
            {
                
if (!(myRead == null)) // 클래스 개체 리소스 해제
                {
                    myRead.Close();
                }
                
if (!(myWrite == null)) // 클래스 개체 리소스 해제
                {
                    myWrite.Close();
                }
                
if (!(myStream == null)) // 클래스 개체 리소스 해제
                {
                    myStream.Close();
                }
                
if (!(SerClient == null)) // 클래스 개체 리소스 해제
                {
                    SerClient.Close();
                }
                
if (!(Server == null)) // 클래스 개체 리소스 해제
                {
                    Server.Stop();
                }
                
if (!(myReader == null)) // 외부스레드 종료
                {
                    myReader.Abort();
                }
                
if (!(myServer == null)) // 외부스레드 종료
                {
                    myServer.Abort();
                }
                
if(!(AddText == null))
                {
                    Invoke(AddText, 
"연결이 끊어졌습니다.");
                }
            }
        }

        
private void Disconnection()
        {
            
this.ClientCon = false;
            
try
            {
                
if (!(myRead == null)) // 클래스 개체 리소스 해제
                {
                    myRead.Close();
                }
                
if (!(myWrite == null)) // 클래스 개체 리소스 해제
                {
                    myWrite.Close();
                }
                
if (!(myStream == null)) // 클래스 개체 리소스 해제
                {
                    myStream.Close();
                }
                
if (!(client == null)) // 클래스 개체 리소스 해제
                {
                    client.Close();
                }
                
if (!(myReader == null)) // 외부스레드 종료
                {
                    myReader.Abort();
                }
            }
            
catch
            {
                
return;
            }
        }
                
        
private void Recieve()
        {
            
try
            {
                
while(this.ClientCon)
                {
                    
if(myStream.CanRead)
                    {
                        var msg 
= myRead.ReadLine();
                        var Smsg 
= msg.Split('&');
                        
if(Smsg[0== "S001")
                        {
                            
this.tsslblTime.Text = Smsg[1];
                        }
                        
else
                        {
                            
if(msg.Length > 0)
                            {
                                Invoke(AddText, Smsg[
0] + ":" + Smsg[1]);
                            }
                            
this.tsslblTime.Text = "마지막으로 받은 시각:" + Smsg[2];
                        }
                    }
                }
            }
            
catch
            {

            }
        }

        
private void MessageView(string strText)
        {
            
this.rtbText.AppendText(strText + "\r\n");
            
this.rtbText.Focus();
            
this.rtbText.ScrollToCaret();
            
this.txtMessage.Focus();
            FlashWindow(
this.Handle, true);
        }

        
private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
        {
            
if(e.KeyChar == (char)13// 엔터키 누를때
            {
                e.Handled 
= true// 소리 없앰
                if(this.txtMessage.Text =="")
                {
                    
this.txtMessage.Focus();
                }
                
else
                {
                    Msg_send(); 
// 함수 호출
                }
            }
        }
        
        
private void btnSend_Click(object sender, EventArgs e)
        {
            
if(this.txtMessage.Text == "")
            {
                
this.txtMessage.Focus();
            }
            
else
            {
                Msg_send(); 
// 함수 호출
            }
        }

        
private void Msg_send()
        {
            
try
            {
                var dt 
= Convert.ToString(DateTime.Now);
                myWrite.WriteLine(
this.myName + "&" + this.txtMessage.Text + "&" + dt);
                myWrite.Flush();
                MessageView(
this.myName + ":" + this.txtMessage.Text);
                
this.txtMessage.Clear();
            }
            
catch
            {
                Invoke(AddText, 
"데이터를 보내는 동안 오류가 발생하였습니다.");
                
this.txtMessage.Clear();
            }
        }

        
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
try
            {
                ServerStop();
            }
            
catch
            {
                Disconnection();
            }
        }

        
private void cbServer_CheckedChanged(object sender, EventArgs e)
        {
            
if(this.cbServer.Checked) // 서버 또는 클라이언트 체크 해제
            {
                
this.txtIp.Enabled = false// 서버모드 전환
            }
            
else
            {
                
this.txtIp.Enabled = true// 클라이언트 모드 전환
            }
        }

        
private void txtMessage_TextChanged(object sender, EventArgs e)
        {
            
if(TextChange== false)
            {
                TextChange 
= true;
                myWrite.WriteLine(
"S001" + "&" + "상대방이 메시지 입력중입니다." + "&" + " ");
                myWrite.Flush();
            }
            
else if(this.txtMessage.Text == "" && TextChange == true)
            {
                TextChange 
= false;
            }
        }
    }
}



http://itsmart333.tistory.com/attachment/cfile25.uf@244CC137559E0CE230FE7F.zip










-client



































=멀티채팅













=

http://itsmart333.tistory.com/attachment/cfile25.uf@2279A950559E1227201A06.zip




==========================================================================================

NETWORK

==========================================================================================


<NETWORK>



http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site


• 리눅스 네트워크 프로그래밍

•  네트워크 프로그래밍 기초 문서들

•  예제로 알아보는 소켓 프로그래밍


=소켓프로그래밍


-SERVER

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
    
int server_sockfd;
    
int client_sockfd;
    
int state, client_len;
    
int pid;

    FILE *fp;
    
struct sockaddr_in clientaddr;
    
struct
 sockaddr_in serveraddr;

    
char buf[255];
    
char line[255];

    
if(argc !=2)
    {
        printf(
"Usage : ./zipcode [port]\n");
        printf(
"예    : ./zipcode 444\n");
        exit(
0);
    }

    memset(line, 
'0',255);
    state 
= 0;

    
//주소파일을 읽어들인다
    client_len = sizeof(clientaddr);
    
if((fp = fopen("zipcode.txt","r")) == NULL)
    {
        perror(
"file open error : ");
        exit(
0);
    }

    
// internet 기반의 소켓 생성(INET)
    if((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror(
"socket error : ");
        exit(
0);
    }
    bzero(
&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family 
= AF_INET;
    serveraddr.sin_addr.s_addr 
= htonl(INADDR_ANY);
    serveraddr.sin_port 
= htons(atoi(argv[1
]));
    
    state 
= bind(server_sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    
if(state == -1)
    {
        perror(
"bind error : ");
        exit(
0);
    }

    state 
= listen(server_sockfd, 5);
    
if(state == -1)
    {
        perror(
"listen error : ");
        exit(
0);
    }

    
while(1)
    {
        client_sockfd 
= accept(server_sockfd, (struct sockaddr *)&clientaddr, &client_len);
        
if(client_sockfd ==-1)
        {
            perror(
"Accept error : ");
            exit(
0);
        }
        
while(1)
        {
            rewind(fp);
            memset(buf, 
'0'255);

            
if(read(client_sockfd, buf, 255<=0)
            {
                close(client_sockfd);
                
break;
            }
            
            
if(strncmp(buf, "quit"4==0)
            {
                write(client_sockfd, 
"bye bye"8);
                close(client_sockfd);
                
break;
            }

            
while(fgets(line, 255, fp) != NULL)
            {
                
if(strstr(line, buf) != NULL)
                {
                    write(client_sockfd, line, 
255);
                }
                memset(line, 
'0'255);
            }
            write(client_sockfd, 
"end"255);
            printf(
"send end\n");
        }
    }

    close(client_sockfd);
    
return 0;
}

-CLIENT

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char ** argv)
{
    
int client_len;
    
int client_sockfd;

    FILE *fp_in;
    
char buf_in[255];
    
char buf_get[255];

    
struct sockaddr_in clientaddr;

    
if(argc !=2)
    {
        printf(
"Usage : ./zipcode_cl [port]\n");
        printf(
"예    : ./zipcode_cl 4444\n");
        exit(
0);
    }

    client_sockfd 
= socket(AF_INET, SOCK_STREAM, 0);
    clientaddr.sin_family 
= AF_INET;
    clientaddr.sin_addr.s_addr 
= inet_addr("127.0.0.1");
    clientaddr.sin_port 
= htons(atoi(argv[1
]));

    client_len 
= sizeof(clientaddr);

    
if(connect(client_sockfd, (struct sockaddr *)&clientaddr, client_len) < 0)
    {
        perror(
"Connect error : ");
        exit(
0);
    }

    
while(1)
    {
        printf(
"지역이름 입력 : ");
        fgets(buf_in, 
255, stdin);

        buf_in[strlen(buf_in)-
1= 0;
        write(client_sockfd, buf_in, 
255);
        
if(strncmp(buf_in, "quit"4==0)
        {
            close(client_sockfd);
            exit(
0);
        }

        
while(1)
        {
            read(client_sockfd, buf_get, 
255);
            
if(strncmp(buf_get, "end"3==0)
            {
                
break;
            }

            printf(
"%s", buf_get);

        }
    }
    close(client_sockfd);
    
return 0;
}







'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150713  (0) 2015.07.14
20150710  (0) 2015.07.12
20150708  (0) 2015.07.08
20150707  (0) 2015.07.08
20150706  (0) 2015.07.07
Posted by ahj333
,

==========================================================================================

AVR

==========================================================================================

<AVR2560>


==AVR Studio 4.19 CONNECT



=MAIN




=Program




-열전대(Thermocoupler) - 다른 두 금속 온도에따라 기전력 발생

 :보상관계(offset)를 eeprom에 저장 (전원 off/on시 데이터 저장되있어야함)

=EEPROM

ex) 끄기 전

A / B

1 / 0

껐다 켜도

A / B

1 / 0



=ELF



=LOCKBITS => READ 금지(복제품 방지)








=Fuses




=경고메세지 뜨는 탭 => 주의





==AVR ISP 다운로드 케이블

-무료

1. AVR Studio + Atmel 매크로 어셈블러 AVRASM2

2. AVR Studio + WinAVR AVR-GCC

3. AVR-ISP Parallel 다운로드 케이블 + ToastProg2005

   직렬포트 AVR-ISP Studio 다운로드 케이블 + AVR Studio

   USB AVR-ISP USB 다운로드 케이블 + AVR Studio


-에뮬레이터

실시간 디버깅 가능


=개발 툴

-CODE VISION AVR - (30만원) - LCD 셋팅가능

www.hpinfotech.com


-IAR

www.iar.com


=병렬 포트 사용 잘 안함(시간 오래 걸림)

(ERASE - PROGRAM - VERIFY)

P359

표.3.2.6


=AVR 4.19 - WIN AVR 되도록 => TOOL CHAIN 설치





=

GPIO

Interrupt

T/C (PWM - DC MOTOR 속도제어 / Remote Controller(적외선 LED - 수광부)-(포토커플러 나눠놓은 형태)

UART

ADC


(ADCONVERT - DIMMING 제어)



=모터제어

-AX-12+

http://itsmart333.tistory.com/attachment/cfile8.uf@2470124A559C9BF4096E79.pdf

http://support.robotis.com/ko/techsupport_kor.htm#product/dynamixel/dxl_mx_main.htm

http://support.robotis.com/ko/



-AX-12+ => 스텝핑모터(자석에 끌려서 동작) - (자동차 계기판 RPM...)

(232 - TTL)

UART TXD







==========================================================================================

C#

==========================================================================================

-일대일채팅


http://itsmart333.tistory.com/attachment/cfile30.uf@277DA64A559C9BE401602D.pdf


==========================================================================================

NETWORK

==========================================================================================

-SOCKET


http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Network_Programing/Documents/Socket_Sample


'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150710  (0) 2015.07.12
20150709  (0) 2015.07.10
20150707  (0) 2015.07.08
20150706  (0) 2015.07.07
20150703  (0) 2015.07.03
Posted by ahj333
,

==========================================================================================

AVR

==========================================================================================

<AVR1280>


(AVR STUDIO 6.2 => ISP  지원 X / 무거움)


WIN AVR

AVR STUDIO 4.19 -> TOOL CHAIN DOWNLOAD


http://www.atmel.com/tools/atmelavrtoolchainforwindows.aspx


=테스트





=






=



=주소확인




=

  

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h
>

ISR(INT0_vect)
{
  
}

int main(void)
{  
  _delay_us(
1000000);
  _delay_ms(
1000);
  
return 0;
}

=

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{  
  DDRA 
= 0xFF;
  
while(1)
  {
    PORTA ^
=0xFF;
    _delay_ms(
1000);
  }

  
return 0;
}


==========================================================================================

C#

==========================================================================================

<C#>


=리플렉션




=새로운 타입을 만든다 : 내가 원하는 메모리 할당 하겠다.

=외부 dll등의 return값 등 알고자 할 때




=클래스 다이어그램



==애트리뷰트

:# 코드단 메타데이타(부가정보)


using System.Runtime.InteropServices;

-DllImport(User32.dll")]

private static extern bool FlashWindow(...);




=>User32.dll(NATIVE CODE - C# 아님) => CLR이 알아보도록 하는 것 ===> DllImport

=>C# => MSIL => CLR (이 알아봄)


-Obsolete("OldMethod는 폐기되었습니다. NewMethod를 사용하세요.“)]




=레지스트리 ( 프로그램 ID/ PWD .... 정보)

-regedit


- 인덱스트리

key(폴더형태) - value






-찾기 : F3






-다음 F3




=ToolStrip










=

using System;
using System.Reflection;

class MainApp
{
  
  //애트리뷰트 선언
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property,
         AllowMultiple 
= true,
         Inherited 
= false)]

    
public class ModifyAttribute : Attribute
    {
        
public ModifyAttribute(string programmer)
        {
            
this.programmer =
 programmer;
        }


        
public string Programmer
        {
            get
            {
                
return programmer;
            }
            set
            {
                programmer 
= value;
            }
        }

        
private string programmer;
    }

    //이 메서드는 박상현과 최우일이 작성했습니다.
    [Modify("박상현"), Modify("최우일")]

    
public static int Add(int a, int b)
    {
        
return a + b;
    }

    //이 메서드는 박상현이 작성했습니다.
    [Modify("박상현")]

    
public static int Minus(int a, int b)
    {
        
return a - b;
    }

    
public static void Main()
    {

        foreach (MethodInfo method in (typeof(MainApp)).GetMethods())
        {
            
object[] myAttributes = method.GetCustomAttributes(typeof(ModifyAttribute), false);

            Console.WriteLine(
"*메서드 이름 : {0}", method.Name);
            foreach (object attribute in myAttributes)
            {
                
ModifyAttribute modifyinfo = (ModifyAttribute)attribute;
                Console.WriteLine(
" 프로그래머 : {0}"modifyinfo.Programmer);
            }
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}

/*

using System;
using System.Reflection;

namespace attribute1
{
    class MainApp
    {
        [AttributeUsage(AttributeTargets.Method 
| AttributeTargets.Property,
        AllowMultiple 
= true,
        Inherited 
= false)]
        public class ModifyAttribute : Attribute
        {
            public ModifyAttribute(string programmer)
            {
                this.programmer 
= programmer;
            }

            public string Programmer
            {
                get
                {
                    return programmer;
                }
                set
                {
                    programmer 
= value;
                }                
            }
            private string programmer;
        }
        //이 메서드는 박상현과 최우일이 작성했습니다.
        [Modify("박상현"), Modify("최우일")]
        public static int Add(int a, int b)
        {
            return a+b;
        }
        //이 메서드는 박상현이 작성했습니다.
        [Modify("박상현")]
        public static int Minus(int a, int b)
        {
            return a - b;
        }
        static void Main(string[] args)
        {
            foreach (MethodInfo method in (typeof(MainApp)).GetMethod())
            {
                object[] myAttributes 
= method.GetCustomAttribute(typeof(ModifyAttribute), false);
                Console.WriteLine("*메서드 이름 : {0}", method.Name);
                foreach(object attribute in myAttributes)
                {
                    ModifyAttribute modifyinfo 
= (ModifyAttribute)attrubute;
                    Console.WriteLine("프로그래머 : {0}", modifyinfo.Programmer);
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

*/





==========================================================================================

NETWORK

==========================================================================================


<NETWORK>



http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site


• 리눅스 네트워크 프로그래밍

•  네트워크 프로그래밍 기초 문서들

•  예제로 알아보는 소켓 프로그래밍


=소켓프로그래밍


=

netinet/in.h

struct sockaddr_in

  {

    __SOCKADDR_COMMON (sin_);

    in_port_t sin_port;         /* Port number.  */

    struct in_addr sin_addr;        /* Internet address.  */:ㅂ


    /* Pad to size of `struct sockaddr'.  */

    unsigned char sin_zero[sizeof (struct sockaddr) -

               __SOCKADDR_COMMON_SIZE -

               sizeof (in_port_t) -

               sizeof (struct in_addr)];

  };






=HOST TO NETWORK =>


/* Address to accept any incoming messages.  */

#define INADDR_ANY      ((in_addr_t) 0x00000000) => 현재 셋팅된 IP알수 없을 때 사용 => 셋팅 된 값가져옴


#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    
unsigned int inum = 0x12345678;
    printf(
"%08x\n",inum);
    printf(
"%08x\n",htonl(inum));

    
return 0;
}









=

1. 소켓생성(IP TCP)

2. IP ADDRESS / PORT 구조체 셋팅

3. bind ( 소켓번호 + 구조체 ) => 소켓 정보 완성


=PORT

-포트번호 -


(트로이 목마 - 실행시 포트문을 연다)


=

PC             -   집          - 집주소       - IP

PROCESS      -  거주자      - 거주자 이름  - PID

PID  : PROCESS ID
























'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150709  (0) 2015.07.10
20150708  (0) 2015.07.08
20150706  (0) 2015.07.07
20150703  (0) 2015.07.03
20150701  (0) 2015.07.02
Posted by ahj333
,

==========================================================================================

NETWORK

==========================================================================================

<NETWORK>



http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site


• 리눅스 네트워크 프로그래밍

•  네트워크 프로그래밍 기초 문서들

•  예제로 알아보는 소켓 프로그래밍


=소켓프로그래밍






=socket() - 소켓 번호 만드는 함수

클라이언트(크롬...) 서버(벽)(구글...)

SC모델 -> SERVER(서비스 제공-하인) - CLIENT(고객)


SOCKET(2)                  Linux Programmer's Manual                 SOCKET(2)


NAME

       socket - create an endpoint for communication


SYNOPSIS

       #include <sys/types.h>         /* See NOTES */

       #include <sys/socket.h>


       int socket(int domain, int type, int protocol);


DESCRIPTION

       socket()  creates  an endpoint for communication and returns a descrip‐

       tor.


       The domain argument specifies a communication domain; this selects  the

       protocol  family  which will be used for communication.  These families

       are  defined  in  <sys/socket.h>.   The  currently  understood  formats

       include:


       Name                Purpose                          Man page

       AF_UNIX, AF_LOCAL   Local communication              unix(7)

       AF_INET             IPv4 Internet protocols          ip(7)

       AF_INET6            IPv6 Internet protocols          ipv6(7)

       AF_IPX              IPX - Novell protocols

       AF_NETLINK          Kernel user interface device     netlink(7)

       AF_X25              ITU-T X.25 / ISO-8208 protocol   x25(7)

       AF_AX25             Amateur radio AX.25 protocol

       AF_ATMPVC           Access to raw ATM PVCs

       AF_APPLETALK        Appletalk                        ddp(7)

       AF_PACKET           Low level packet interface       packet(7)


       The  socket  has  the indicated type, which specifies the communication

       semantics.  Currently defined types are:


       SOCK_STREAM     Provides sequenced, reliable, two-way, connection-based

                       byte  streams.  An out-of-band data transmission mecha‐

                       nism may be supported.


       SOCK_DGRAM      Supports datagrams (connectionless, unreliable messages

                       of a fixed maximum length).


       SOCK_SEQPACKET  Provides  a  sequenced,  reliable,  two-way connection-

                       based data transmission path  for  datagrams  of  fixed

RETURN VALUE

       On  success,  a file  descriptor (저수준) for  the new socket is returned.  On

       error, -1 is returned, and errno is set appropriately.








=grep

-찾고싶은 문자열에 "" - 띄어쓰기 있는 경우

-r : 하위디렉토리까지 검색







GREP(1)                                                                GREP(1)


NAME

       grep, egrep, fgrep, rgrep - print lines matching a pattern


SYNOPSIS

       grep [OPTIONS] PATTERN [FILE...]

       grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]


DESCRIPTION

       grep  searches the named input FILEs (or standard input if no files are

       named, or if a single hyphen-minus (-) is given as file name) for lines

       containing  a  match to the given PATTERN.  By default, grep prints the

       matching lines.


       In  addition,  three  variant  programs  egrep,  fgrep  and  rgrep  are

       available.   egrep  is  the  same  as  grep -E.   fgrep  is the same as

       grep -F.  rgrep is the same as grep -r.  Direct  invocation  as  either

       egrep  or  fgrep  is  deprecated,  but  is provided to allow historical

       applications that rely on them to run unmodified.


OPTIONS

   Generic Program Information

       --help Print a usage message  briefly  summarizing  these  command-line

              options and the bug-reporting address, then exit.


       -V, --version

              Print  the version number of grep to the standard output stream.

              This version number should be included in all bug  reports  (see

              below).


   Matcher Selection

       -E, --extended-regexp

              Interpret  PATTERN  as  an extended regular expression (ERE, see

              below).  (-E is specified by POSIX.)


       -F, --fixed-strings

              Interpret PATTERN as a  list  of  fixed  strings,  separated  by

              newlines,  any  of  which is to be matched.  (-F is specified by

              POSIX.)


       -G, --basic-regexp

              Interpret PATTERN  as  a  basic  regular  expression  (BRE,  see

              below).  This is the default.


       -P, --perl-regexp

              Interpret  PATTERN  as  a  Perl  regular  expression  (PCRE, see

              below).  This is highly experimental and grep  -P  may  warn  of

              unimplemented features.



=






=SOCK_STREAM

=



   



-TCP(TCP/IP)

SOCK_STREAM = 1,      /* Sequenced, reliable, connection-based

                    byte streams.  */

-UDP(UDP/IP...-> 노래.. 영화감상...)

SOCK_DGRAM = 2,       /* Connectionless, unreliable datagrams

                    of fixed maximum length.  */




==NETWORK

=IPC -Inter Process Comunication ( 내부에서 대화 )

창                      <-Data->      창

실행 - 프로세스                         프로세스

=NETWORK - 다른 PC 간


하드 - 프로그램


=IPC의 일부 => PIPE


=PF_UNIX => IPC로 동작 (UNIX슈퍼컴퓨터에 단말기가 붙어서 있었음)-> IPC

=X.25 => 화상회의

=ATM=> 중계기(고속)


=유닉스 - 헤더파일 존재

=WINDOWS에서는 헤더파일 존재하지 않는 경우 있음 (생으로 써줘야함)



#define SOCK_DGRAM SOCK_DGRAM

  SOCK_RAW = 3,        /* Raw protocol interface.  *///가공X - (틀(봉투)만 만들고 내용(주소)은 안채워넣음)

#define SOCK_RAW SOCK_RAW

  SOCK_RDM = 4,         /* Reliably-delivered messages.  */

#define SOCK_RDM SOCK_RDM

  SOCK_SEQPACKET = 5,       /* Sequenced, reliable, connection-based,

                   datagrams of fixed maximum length.  */

#define SOCK_SEQPACKET SOCK_SEQPACKET

  SOCK_DCCP = 6,        /* Datagram Congestion Control Protocol.  */

#define SOCK_DCCP SOCK_DCCP

  SOCK_PACKET = 10,     /* Linux specific way of getting packets

                   at the dev level.  For writing rarp and

                   other similar things on the user level. */

#define SOCK_PACKET SOCK_PACKET


  /* Flags to be ORed into the type parameter of socket and socketpair and

     used for the flags parameter of paccept.  */


  SOCK_CLOEXEC = 02000000,  /* Atomically set close-on-exec flag for the

                   new descriptor(s).  */

#define SOCK_CLOEXEC SOCK_CLOEXEC

  SOCK_NONBLOCK = 04000     /* Atomically mark descriptor(s) as

                   non-blocking.  */

#define SOCK_NONBLOCK SOCK_NONBLOCK



=

1. 연결 작업 -

2. 데이터 교환 - READ / WRITE

3. 해제 작업 - CLOSE



=

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    printf(
"errno : %d\n",errno);
    open(
"kkkk", O_RDONLY);
    printf(
"errno : %d\n",errno);

    
return 0;
}







=perror




#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    printf(
"errno : %d\n",errno);
    open(
"kkkk", O_RDONLY);
    printf(
"errno : %d\n",errno);
   
 errno = EADDRINUSE;
   
 perror("smart");
    
return 0;
}














=



==========================================================================================

C#

==========================================================================================

<C#>


=FILEINFO

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace FILE08_filefind
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            lstView.Clear();
            lstView.View 
= View.Details;
            lstView.CheckBoxes 
= true;
            lstView.FullRowSelect 
= true;
            lstView.GridLines 
= true;
            lstView.Sorting 
= SortOrder.Ascending;
            lstView.Columns.Add(
"파일명"170, HorizontalAlignment.Left);
            lstView.Columns.Add(
"파일크기"80, HorizontalAlignment.Right);
            lstView.Columns.Add(
"수정일자"150, HorizontalAlignment.Left);
        }

        
void FindFile(string str)
        {
            string dir 
= txt_dir.Text.Trim();
            
if(dir=="")
            {
                MessageBox.Show(
"검색디렉토리를 입력하세요!");
                
return;
            }
            string[] files_list;
            files_list 
= Directory.GetFiles(dir, str);
            
for(int i=0; i < files_list.Length;++i)
            {
                ListViewItem item1 
= new ListViewItem(files_list[i], 0);

                var info 
= new FileInfo(item1.Text);//from file in Directory.GetFiles(item1.Text)//@item1.Text                             
                
                item1.SubItems.Add(info.Length.ToString());
                item1.SubItems.Add(info.LastWriteTime.ToString());
                lstView.Items.Add(item1);

            }            
        }

        
private void btn_search_Click(object sender, EventArgs e)
        {
            
if(txt_filename.Text != "")
            {
                lstView.Items.Clear();
                FindFile(txt_filename.Text);
            }
        }
    }
}





=NETWORK







=65535(장비별로 달라짐) => PORT개수(문 없는 상태)

=문(출구, 입구 , 출입구) 생성 => 소켓



=DNS

-nslookup






=




=






-

using System;
using System.Net;

namespace network
{
    
class Program
    {
        
static void Main(string[] args)
        {
            IPAddress ex1 
= IPAddress.Parse("192.168.0.169");
    
        IPAddress ex2 = IPAddress.Any;
            IPAddress ex3 
= IPAddress.Broadcast;
            IPAddress ex4 
= IPAddress.Loopback;
            IPAddress ex5 
= IPAddress.None;

            Console.WriteLine(
"{0}={1}""ex1", ex1);
            Console.WriteLine(
"{0}={1}""ex2(Any)", ex2);
            Console.WriteLine(
"{0}={1}""ex3(Broadcast)", ex3);
            Console.WriteLine(
"{0}={1}""ex4(Loopback)", ex4);
            Console.WriteLine(
"{0}={1}""ex5(None)", ex5);
        }
    }
}






=




using System;
using System.Net;

namespace network2
{
    
class Program
    {
        
static void Main(string[] args)
        {
            IPAddress ex 
= IPAddress.Parse("192.168.0.169");
            
IPEndPoint ie = new IPEndPoint(ex, 8000); // 로컬주소를 바인드하거나 소켓과 원격주소를 연결시 사용
            Console.WriteLine("ToString()    :{0}", ie.ToString());
            Console.WriteLine(
"AddressFamily :{0}", ie.AddressFamily);
            Console.WriteLine(
"Address       :{0}", ie.Port);
            Console.WriteLine(
"MaxPort() :{0} MinPort() :{1}"IPEndPoint.MaxPort,
                IPEndPoint.MinPort);

        }
    }
}





=






=복사기 ...(렌케이블 장비)




=


=별로 사용은 안함







=Buffered CLASS (읽기, 파일) => 대용량처리

 - Flush()







=




=




'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150708  (0) 2015.07.08
20150707  (0) 2015.07.08
20150703  (0) 2015.07.03
20150701  (0) 2015.07.02
20150630  (0) 2015.06.30
Posted by ahj333
,

==========================================================================================

C#

==========================================================================================


<C#>



=스레드 동기화





-cf)mutex object - 스레드 동시 접근 불가능



-lock 사용






-lock 사용 X






==파일













=스트림

-메모리에서 하드디스크로 데이터를 옮길 때 스트림을 만들어 둘 사이를 연결한 뒤 메모리의 데이터를 바이트 단위로 하드디스크로 옮김.


-Wrapper class(어떤 언어로 해야할지 정할수 있음)


=

using System;
using System.IO;

namespace FILE01_directoryinfo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            DirectoryInfo dinfo 
= new DirectoryInfo(@"C:\TC\LIB");
            
if (dinfo.Exists)
            {
                Console.WriteLine(
"전체 경로      : {0}", dinfo.FullName);
                Console.WriteLine(
"디렉토리 이름  : {0}", dinfo.Name);
                Console.WriteLine(
"생성일         : {0}", dinfo.CreationTime);
                Console.WriteLine(
"디렉토리 속성  : {0}", dinfo.Attributes);
                Console.WriteLine(
"루트 경로      : {0}", dinfo.Root);
                Console.WriteLine(
"부모 디렉토리  : {0}", dinfo.Parent);
            }
            
else
            {
                Console.WriteLine(
"디렉토리가 존재하지 않습니다");
            }
            Console.ReadLine();
        }
    }
}







=

using System;
using System.IO;

namespace FILE02_fileinfo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            FileInfo finfo 
= new FileInfo(@"C:\TC\LIB\CC.LIB");
            
if (finfo.Exists)
            {
                Console.WriteLine(
"폴더 이름      : {0}", finfo.Directory);
                Console.WriteLine(
"파일 이름      : {0}", finfo.Name);
                Console.WriteLine(
"확장자         : {0}", finfo.Extension);
                Console.WriteLine(
"생성일         : {0}", finfo.CreationTime);
                Console.WriteLine(
"파일 크기      : {0}", finfo.Length);
                Console.WriteLine(
"파일 속성      : {0}", finfo.Attributes);
            }
            
else
            {
                Console.WriteLine(
"파일이 존재하지 않습니다");
            }
        }
    }
}







=

using System;
using System.IO;

namespace FILE03_drectory_fileinfo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
if(args.Length < 1)
            {
                Console.WriteLine(
"사용법 : FileExam3.exe [디렉토리 경로]");
                
return;
            }
            DirectoryInfo dinfo 
= new DirectoryInfo(args[0]);
            
if(dinfo.Exists)
            {
                DirectoryInfo[] dir 
= dinfo.GetDirectories()// 하위디렉토리 파일 정보 출력
                foreach(DirectoryInfo d in dir)
                {
                    FileInfo[] files 
= d.GetFiles();
                    Console.WriteLine(
"디렉토리 : {0}, 포함된 파일 수: {1}", d.FullName, files.Length);

                    
int index = 0;
                    foreach(FileInfo f in files)
                    {
                        string str 
= string.Format("[{0}] : Name:{1}, Ext:{2}, Size:{3},                                                                                        ++index, f.Name, f.Extension, f.Length);
                        Console.WriteLine(str);
                    }
                }
            }
        }
    }
}


=C#매개변수










=

using System;
using System.IO;
using System.Linq;

namespace FILE05_dir_fileinfo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            string directory;
            
if (args.Length < 1)
                directory 
= ".";
            
else
                directory = args[0];

            Console.WriteLine(
"{0} drectory Info", directory);
            Console.WriteLine(
"= Directoris :");
            var directories 
= (from dir in Directory.GetDirectories(directory)
            let info 
= new DirectoryInfo(directory)
            select 
new
            {
                Name 
= info.Name,
                Attributes 
=
 info.Attributes
            }).ToList();

            foreach (var d in directories)
                Console.WriteLine(
"{0} : {1}", d.Name, d.Attributes);

            Console.WriteLine(
"- Files :");
            var files 
= (from files in Directory.GetFiles(directory)
                         let info 
= new FileInfo(file)
                         select 
new
                         {
                             Name 
= info.Name,
                             FileSize 
= info.Length,
                             Attributes 
=
 info.Attributes,
                         }).ToList();

            foreach (var f in files)
                Console.WriteLine(
"{0} : {1}, {2}",
                    f.Name, f.FileSize, f.Attributes);
        }
    }
}







=

using System;
using System.IO;
using System.Linq;

namespace FILE05_dir_fileinfo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            string directory;
            
if (args.Length < 1)
                directory 
= ".";
            
else
                directory = args[0];

            Console.WriteLine(
"{0} drectory Info", directory);
            Console.WriteLine(
"= Directoris :");
            var directories 
= (from dir in Directory.GetDirectories(directory)
                        let info 
= new DirectoryInfo(dir)
                        select 
new
                        {
                            Name 
= info.Name,
                            Attributes 
=
 info.Attributes
                        }).ToList();


            foreach (var d in directories)
                Console.WriteLine(
"{0} : {1}", d.Name, d.Attributes);

            Console.WriteLine(
"- Files :");
            var files 
= (from file in Directory.GetFiles(directory)
                         let info 
= new FileInfo(file)
                         select 
new
                         {
                             Name 
= info.Name,
                             FileSize 
= info.Length,
                             Attributes 
=
 info.Attributes,
                         }).ToList();

            foreach (var f in files)
                Console.WriteLine(
"{0} : {1}, {2}",
                    f.Name, f.FileSize, f.Attributes);
        }
    }
}




=Create file / directory


-test.dat





-




-test Directory






=

http://www.codeproject.com/Articles/33786/DataGridView-Filter-Popup




http://www.codeproject.com/Articles/51889/Summary-DataGridView


http://www.codeproject.com/Articles/19735/DataGridView-with-Detail-Edit-Form-VS


'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150707  (0) 2015.07.08
20150706  (0) 2015.07.07
20150701  (0) 2015.07.02
20150630  (0) 2015.06.30
2015029  (0) 2015.06.30
Posted by ahj333
,