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

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
,