posted by 방랑군 2012. 1. 6. 23:36
1. Uploadify.htm
<head>
    <title>파일업로드 : jQuery + Uploadify + ASP.NET</title>
    <link href="uploadify.css" rel="stylesheet" type="text/css" />
    
    <script type="text/ecmascript" src="jquery-1.4.2.min.js"></script>
    <script src="jquery.uploadify.v2.1.4.js" type="text/javascript"></script>
    <script src="swfobject.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // Uploadify 파일 업로드 컨트롤 : Flash가 설치가 되어있어야 함
            $('#fileInput').uploadify({
                'uploader': 'uploadify.swf', // Uploadify 컨트롤 지정
                'script': 'Uploadify.ashx', // 서버측 스크립트, ASP.NET, ASP, PHP, JSP
                'cancelImg': 'cancel.png', // 취소 이미지
                'auto': false, // true면 파일선택시 바로 자동으로 업로드됨
                'folder': '/Uploads', // 업로드할 폴더 : 가상디렉터리 + 업로드폴더
                // 업로드 완료시 처리 :
                //      주요 속성은 http://www.uploadify.com/documentation/ 참고
                'onComplete': function (event, queueID, fileObj, response, data) {
                    $('#lblFile').append('<a href=/WebJQuery' + fileObj.filePath + '>'
                    + fileObj.name + '</a><br>');
                }
            });
            // 버튼 클릭시 업로드
            $('#btn').click(function () { $('#fileInput').uploadifyUpload(); });
        });
    </script>
</head>
<body>
    <input id="fileInput" name="fileInput" type="file" />
    <input type="button" id="btn" value="업로드" />
    <div id="lblFile"></div>
</body>
</html>

2. Uploadify.ashx
<%@ WebHandler Language="C#" Class="Uploadify" %>
 
using System;
using System.Web;
 
public class Uploadify : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        // Filedata로 넘겨온 파일 값 받기
        HttpPostedFile file = context.Request.Files["Filedata"];
        // 저장할 폴더
        string targetDirectory = System.IO.Path.Combine(
        context.Request.PhysicalApplicationPath,
        context.Request["folder"].Replace("/", ""));
        // 저장할 폴더 + 파일명
        string targetFilePath = System.IO.Path.Combine(
            targetDirectory, file.FileName);
        // 파일 저장(업로드)
        file.SaveAs(targetFilePath);
 
        context.Response.Write("RedPlus");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
 

'PP > Upload' 카테고리의 다른 글

실시간 파일 업로드 - uploadify  (0) 2012.01.04
posted by 방랑군 2012. 1. 6. 23:22

출처 : http://infosearchshop.com/Content.aspx?id=7vWHuJea+Lw=&title=Making+thumbnail+dynamically+with+ashx+file+in+asp.net

 

In this article I am going to show how to resize image dynamically or making thumbnail dynamically with ashx file.Start new website project give name thumbnail.In menu go to Webite > Add new item and select Generic Handler. Name it Handler.ashx, You will get auto generated code in it like given below:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


Now add given namespace to handle the image files
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

 

Make a new folder for images files, name it images. Put some images in this folder.

Now our next step is getting the height , width , image name and changing image size.
 To do these things, here query string is used. In ProcessRequest method write follwing lines.

 

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
 // for new height of image
  int h=int.Parse(context.Request.QueryString["h"].ToString()); 
 // for new width of image
        int w = int.Parse(context.Request.QueryString["w"].ToString());
         // for  image file name
        string file = context.Request.QueryString["file"].ToString();

 // Path of image folder where images files are placed
 string  filePath = context.Server.MapPath("~/images/" + file);

 // Resize proccess
   using(System.Drawing.Image img=System.Drawing.Image.FromFile(filePath))
    {
       Bitmap objBmp = new Bitmap(img,w, h);
        string extension = Path.GetExtension(filePath);
        MemoryStream ms; 
        byte[] bmpBytes;
        switch (extension.ToLower())
        {
            case ".jpg":
            case ".jpeg": 
                ms = new MemoryStream();
                objBmp.Save(ms, ImageFormat.Jpeg);
                bmpBytes = ms.GetBuffer();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(bmpBytes);
                objBmp.Dispose();
                ms.Close();
                context.Response.End();
                break;
            case ".png":
                  ms = new MemoryStream();
                  objBmp.Save(ms, ImageFormat.Png);
                  bmpBytes = ms.GetBuffer();
                 context.Response.ContentType = "image/png";
                 context.Response.BinaryWrite(bmpBytes);
                 objBmp.Dispose();
                 ms.Close();
                 context.Response.End();
            break;
           case ".gif":
                ms = new MemoryStream();
                objBmp.Save(ms, ImageFormat.Gif);
                bmpBytes = ms.GetBuffer();
                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(bmpBytes);
                objBmp.Dispose();
                ms.Close();
                context.Response.End();
                break;
  
        }
        img.Dispose();
   }

    }

 

Now we move to Default.aspx page, drag here  Image tool from tool box :

    <asp:Image ID="img1" runat="server" /><br />
For retriving the image set ImageUrl as given below with height width and image name.

<asp:Image ID="img1" runat="server" ImageUrl="~/Handler.ashx?h=50&w=50&file=Winter.jpg" /><br />

And now finally run the default.aspx and see the result.

posted by 방랑군 2012. 1. 6. 23:21

출처 : http://www.west-wind.com/weblog/posts/283.aspx

 

 

One frequent task is to take images and convert them into thumbnails. This is certainly nothing new, but seeing this question is so frequently asked on newsgroups and message boards bears reviewing this topic here again.

 

I was getting tired of constantly repeating this code for specific situations, so I created a generic page in my apps to handle resizing images from the current site dynamically in a page called CreateThumbnail. You call this page with a relative image name from the Web site on the querystring and it returns the image as a thumbnail.

 

An example of how this might work looks like this:

 

http://www.west-wind.com/wwStore/demos/CreateThumbnail.aspx?image=images/WebStoreLogo_big.jpg&size=400

 

Size is an optional second parameter – it defaults to 120.

 

Here’s what the implementation of this generic page looks like:

 

using System.Drawing;

using System.Drawing.Imaging;

 

public class CreateThumbNail : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e)

      {

            string Image = Request.QueryString["Image"];

            if (Image == null

            {

                  this.ErrorResult();

                  return;

            }

 

            string sSize = Request["Size"];

            int Size = 120;

            if (sSize != null)

                  Size = Int32.Parse(sSize);

 

            string Path = Server.MapPath(Request.ApplicationPath) + "\\" + Image;

            Bitmap bmp = CreateThumbnail(Path,Size,Size);

 

            if (bmp == null)

            {

                  this.ErrorResult();

                  return;

            }

 

            string OutputFilename = null;

            OutputFilename = Request.QueryString["OutputFilename"];

 

            if (OutputFilename != null)

            {

                  if (this.User.Identity.Name == ""

                  {

                        // *** Custom error display here

                        bmp.Dispose();

                        this.ErrorResult();

                  }

                  try

                  {

                        bmp.Save(OutputFilename);

                  }

                  catch(Exception ex)

                  {

                        bmp.Dispose();

                        this.ErrorResult();

                        return;

                  }

            }

 

            // Put user code to initialize the page here

            Response.ContentType = "image/jpeg";

            bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

            bmp.Dispose();

      }

 

      private void ErrorResult()

      {

            Response.Clear();

            Response.StatusCode = 404;

            Response.End();

      }

 

      ///

      /// Creates a resized bitmap from an existing image on disk.

      /// Call Dispose on the returned Bitmap object

      ///

      ///

      ///

      ///

      /// Bitmap or null

      public static Bitmap CreateThumbnail(string lcFilename,int lnWidth, int lnHeight)

      {

     

            System.Drawing.Bitmap bmpOut = null;

            try

            {

                  Bitmap loBMP = new Bitmap(lcFilename);

                  ImageFormat loFormat = loBMP.RawFormat;

 

                  decimal lnRatio;

                  int lnNewWidth = 0;

                  int lnNewHeight = 0;

 

                  //*** If the image is smaller than a thumbnail just return it

                  if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)

                        return loBMP;

           

 

                  if (loBMP.Width > loBMP.Height)

                  {

                        lnRatio = (decimal) lnWidth / loBMP.Width;

                        lnNewWidth = lnWidth;

                        decimal lnTemp = loBMP.Height * lnRatio;

                        lnNewHeight = (int)lnTemp;

                  }

                  else

                  {

                        lnRatio = (decimal) lnHeight / loBMP.Height;

                        lnNewHeight = lnHeight;

                        decimal lnTemp = loBMP.Width * lnRatio;

                        lnNewWidth = (int) lnTemp;

                  }

 

                  // System.Drawing.Image imgOut =

                  //      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,

                  //                              null,IntPtr.Zero);

                 

                  // *** This code creates cleaner (though bigger) thumbnails and properly

                  // *** and handles GIF files better by generating a white background for

                  // *** transparent images (as opposed to black)

                  bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

                  Graphics g = Graphics.FromImage(bmpOut);

                  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                  g.FillRectangle( Brushes.White,0,0,lnNewWidth,lnNewHeight);

                  g.DrawImage(loBMP,0,0,lnNewWidth,lnNewHeight);

 

                  loBMP.Dispose();

            }

            catch

            {

                  return null;

            }

     

            return bmpOut;

      }

 

}

 

This code doesn’t use the CreateThumbnail method of GDI+ because it doesn’t properly convert transparent GIF images as it draws the background color black. The code above compensates for this by first drawing the canvas white then loading the GIF image on top of it. Transparency is lost – unfortunately GDI+ does not handle transparency automatically and keeping Transparency intact requires manipulating the palette of the image which is beyond this demonstration.

 

The Bitmap object is returned as the result. You can choose what to do with this object. In this example it’s directly streamed in the ASP. Net Output stream by default. If you specify another query string value of OutputFilename you can also force the file to be written to disk *if* you are logged in. This is definitely not something that you want to allow just ANY user access to as anything that writes to disk is potentially dangerous in terms of overloading your disk space. Writing files out in this fashion also requires that the ASPNET or NETWORK SERVICE or whatever account the ASP. Net app runs under has rights to write the file in the specified directory. I’ve provided this here as an example, but it’s probably best to stick file output functionality into some other more isolated component or page that is more secure.

 

Notice also that all errors return a 404 file not found error. This is so that images act on failure just as if an image file is not available which gives the browser an X’d out image to display. Realistically this doesn’t matter – browsers display the X anyway even if you send back an HTML error message, but this is the expected response the browser would expect.

 

In my West Wind Web Store I have several admin routines that allow to resize images on the fly and display them in a preview window. It’s nice to preview them before writing them out to disk optionally. You can also do this live in an application *if* the number of images isn’t very large and you’re not pushing your server to its limits already. Image creation on the fly is always slower than static images on disk. However, ASP. Net can be pretty damn efficient using Caching and this scenario is made for it. You can specify:

<%@ OutputCache duration="10000" varybyparam="Image;Size" %>

 

in the ASPX page to force images to cache once they’ve been generated. This will work well, but keep in mind that bitmap images can be memory intensive and caching them can add up quickly especially if you have large numbers of them.

 

If you create images dynamically frequently you might also consider using an HTTP Handler to perform this task since raw Handlers have less overhead than the ASP.Net Page handler. For example, the Whidbey Dynamic Image control relies on an internal handler that provides image presentation 'dynamically' without having to save files to disk first.

posted by 방랑군 2012. 1. 6. 23:21

출처 : http://ryunad.tistory.com/tag/C%23%20%EC%9D%B4%EB%AF%B8%EC%A7%80%20%EC%8D%B8%EB%84%A4%EC%9D%BC

 

 

간단하게 이미지를 하나 선택하면 선택한 이미지의 Thumbnail을 만드는 로직입니다.

윈 폼으로 만들었지만 로직부분만 재활용하면 ASP.NET이든 WPF든 어디서든 사용이 가능합니다.

 

 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Runtime.Serialization.Formatters.Binary;

using System.IO;

namespace Ex11 

    public partial class MainForm : Form 
    { 
        private Person _person = new Person();

        public MainForm() 
        { 
            InitializeComponent(); 
        }

        private void btnLoadPicture_Click(object sender, EventArgs e) 
        { 
            //1. 파일 불러오기 
            OpenFileDialog dlg = new OpenFileDialog(); 
            if (DialogResult.OK == dlg.ShowDialog()) 
            { 
                string path = Application.StartupPath;

                string fileName = 
                    dlg.FileName.Substring( 
                    dlg.FileName.LastIndexOf("\\") + 1); 
                string filePath = 
                    Path.Combine(path, fileName); 
                int dotPosition = fileName.LastIndexOf("."); 
                string thumbnailName = 
                    fileName.Substring(0, dotPosition) + 
                    "_small" + 
                    fileName.Substring(dotPosition); 
                string thumbnailPath = 
                    Path.Combine(path, thumbnailName); 
                if (File.Exists(filePath)) 
                    File.Delete(filePath); 
                //2. 원본이미지 복사 및 thumbnail 이미지 생성 
                File.Copy(dlg.FileName, filePath); 
                Image image = 
                    Image.FromFile(filePath); 
                Image thumbnail = 
                    image.GetThumbnailImage(150, 150, null, IntPtr.Zero); 
                //picture 이미지 해제 
                if (pbPicture.Image != null) 
                { 
                    pbPicture.Image.Dispose(); 
                } 
                if (File.Exists(thumbnailPath)) 
                    File.Delete(thumbnailPath); 
                thumbnail.Save(thumbnailPath);

                //이미지 객체의 해제 
                image.Dispose(); 
                thumbnail.Dispose(); 
                //3. 이미지 표시 
                pbPicture.Image = 
                    Image.FromFile(thumbnailPath);

                _person.ImagePath = fileName; 
            } 
        }

        private void miSave_Click(object sender, EventArgs e) 
        { 
            _person.Name = txtName.Text; 
            _person.ResidentNumbers = txtResidentNumber.Text; 
            _person.BirthDate = DateTime.Parse(txtBirthDate.Text); 
            _person.Height = int.Parse(txtHeight.Text); 
            _person.Weight = int.Parse(txtWeight.Text); 
            _person.Phone = txtPhone.Text; 
            _person.Email = txtEmail.Text;

            string path = Path.Combine(Application.StartupPath, "person.dat"); ; 
            FileStream stream = new FileStream(path, FileMode.Create); 
            BinaryFormatter formatter = new BinaryFormatter(); 
            formatter.Serialize(stream, _person); 
            stream.Close();

            MessageBox.Show("저장되었습니다."); 
        }

        private void miOpen_Click(object sender, EventArgs e) 
        { 
        }

        private void MainForm_Load(object sender, EventArgs e) 
        { 
            string path = Path.Combine(Application.StartupPath,"person.dat"); 
            if (File.Exists(path)) 
            { 
                FileStream stream = new FileStream(path, FileMode.Open); 
                BinaryFormatter formatter = new BinaryFormatter(); 
                _person = (Person)formatter.Deserialize(stream); 
                txtName.Text = _person.Name; 
                txtResidentNumber.Text = _person.ResidentNumbers; 
                txtBirthDate.Text = _person.BirthDate.ToString("yyyy-MM-dd"); 
                txtHeight.Text = _person.Height.ToString(); 
                txtWeight.Text = _person.Weight.ToString(); 
                txtPhone.Text = _person.Phone; 
                txtEmail.Text = _person.Email;

                string fileName = _person.ImagePath; 
                fileName = fileName.Insert(fileName.LastIndexOf("."), "_small"); 
                string imagePath = Path.Combine(Application.StartupPath, fileName); 
                if (File.Exists(imagePath)) 
                { 
                    pbPicture.Image = Image.FromFile(imagePath); 
                } 
            } 
        } 
    } 
}

[출처] C# 이미지 섬네일|작성자 괴무리

'PP > ASP.NET' 카테고리의 다른 글

[asp.net] ashx 이미지 섬네일  (0) 2012.01.06
[asp.net] 이미지 섬네일  (0) 2012.01.06
[.ASHX 파일]jQuery 제너릭 처리기(ashx)로 DB/데이터배이스 받기/사용 핸들러/handler  (0) 2012.01.06
GENERIC  (0) 2012.01.04
Generic  (0) 2012.01.04
posted by 방랑군 2012. 1. 6. 23:20
출처 :   http://blog.yahoo.com/_SPX445PUEEEIIXT52JGVCSUPBQ/articles/503589 

Handler를 이용한 방법은 제가 자세한 원리는 잘 모르기 때문에 사용예제만 하나 올리겠습니다.

aspx페이지를 안만들고 ashx를 만들면 성능상 더 좋다고 합니다.

우선 ashx파일을 만듭니다.



넵 만들고 나면 기본적으로 이런코드만 나옵니다.
여기서 우선 알아두셔야할게 빨강 네모에 이 ashx파일이 내놓는 자료형식을 코드해주셔야 합니다.
저는 JSON형식을 사용하기 때문에 text/json으로 코드하겠습니다.
초록색 네모부분에는 출력할 결과문이 들어갈 자리입니다.



그런데 기본코드에서 빠진부분이 있습니다. 밑에 그림처럼 인코딩형식을 UTF8로 맞춰저야 합니다.
밑에 초록색은 안넣으셔도 상관없지만 보안상 넣어주시는게 좋다고 합니다.(정확히는 저도 잘 ^^;;)
여기까지가 밑준비 입니다.
원본 크기의 사진을 보려면 클릭하세요

이제 위쪽에 우리가 정말로 알고싶은 정보를 받아와서 JSON형식으로 바꿔주시면 됩니다.
그리고 다 바꾸고 나서는 꼭 Write메서드의 괄호안을 바꿔줍시다.
저는 다 알맞게 해놓고, 그부분을 빼먹어서 계속 Hello World가 나오더군요;;

원본 크기의 사진을 보려면 클릭하세요


넵 이걸로 ashx는 끝났습니다. 이제 받아서 사용하시기만 하면 됩니다.
jQuery에서 받아서 사용하는 방법은 예전에 올린 호스팅이랑 똑같습니다. 물론 불러올 페이지는 전에 aspx에서
이번에 만든 ashx파일경로로 바꿔주셔야 하죠 ^^


 

'PP > ASP.NET' 카테고리의 다른 글

[asp.net] ashx 이미지 섬네일  (0) 2012.01.06
[asp.net] 이미지 섬네일  (0) 2012.01.06
C# 이미지 섬네일  (0) 2012.01.06
GENERIC  (0) 2012.01.04
Generic  (0) 2012.01.04
posted by 방랑군 2012. 1. 6. 23:02


System.IO.FileStream
System.IO.MemoryStream
System.IO.BufferedStream
System.Net,Sockets.NetworkStream
System.Security,Cryptography.CryptoStream : 암호화 객체를 스트림으로 다룬다. 
posted by 방랑군 2012. 1. 6. 22:06
       // 서버 TCP 리스너
        private TcpListener _server = null;
.
.
.
              // TcpListener로 서버 객체를 생성합니다.
                _server = new TcpListener(localHostEntry.AddressList[0], _svrPort);
.
.
.
         // 실제 스레드가 처리되는 메소드
        private void ServerThreadStart()
        {
            // 클라이언트 소켓 객체를 선언합니다.
            Socket clientSocket = null;

            while (!_isStop)
            {
                try { 
                
                    // 서버에 접속된 클라이언트 소켓을 받습니다.
                    clientSocket = _server.AcceptSocket();    //<-- 대기상태
                         : while 돌면서 이부분에서 대기 상태에 있다가 Client에서
                         (TcpClient _tcpClient = new TcpClient(_svrIP, _svrPort);)이 부분을 만나 Connect 하면서 다음
                         줄 명령라인으로 이동된다.

==> 설명 
clientSocket = _server.AcceptSocket();   이 곳에서 주구장창 클라이언트들을 기다린다.
 접속될때마다 각각 클라이언트들은  클라이언트마다 틀린 RemoteEndPoint ( IP :PORT)  즉, 포트만 틀린 종점을 받아
 서로 연결되어 수행이 이루어진다.  이때의 PORT 는 실제(컴퓨터) PORT 가 아닌 가상(SOCKET) PORT 이다.

Connection.LocalEndPoin는 자신의 IP와 Port를 표시하고, 
Connection.RemoteEndPoint는 자신의 LocalEndPoint에 접속된 다른 Socket의 IP와포트를 나타냅니다. 

 LocalEndPoin : 컴퓨터의 IP, PORT
RemoteEndPoint : SOCKET 의 IP, PORT <-- 여러 클라이언트 구별 키.



 
posted by 방랑군 2012. 1. 6. 17:51

1.  // 소켓에 관련된 스레드가 돌고 있으므로 application 스레드와의 충돌을 피하기 위해 델리게이트를 이용 

        // 어플리케이션의 스레드에 포함되기 위해 델리게이트 이용
        public void LogWrite(string msg)
        { 
            // 소켓에 관련된 스레드가 돌고 있으므로 application 스레드와의 충돌을 피하기 위해 델리게이트를 이용합니다.
            LogWriteDelegate deleLogWirte = new LogWriteDelegate(AppendLog);
            // 생성한 델리케이트를 이용하여 invoke를 실행합니다.
            this.Invoke(deleLogWirte, new object[] { msg });
        }

        // 로그를 찍고 스크롤된 위치에 위치하도록 합니다.
        public void AppendLog(string msg)
        {
            try
            {
                txtOutput.AppendText(msg + "\r\n");
                txtOutput.Focus();
                txtOutput.ScrollToCaret();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        } 

2.
private void Form1_Load(object sender, EventArgs e)
{
            Thread t1 = new Thread(new ThreadStart(Listen));
            t1.Start();
} 

public void Listen()
{
            adtx ad = new adtx(textBox1.AppendText);
           
            IPAddress addr = new IPAddress(0);
            TcpListener server = new TcpListener(addr, 5425);
            server.Start();


            Invoke(ad, "서버시작");

            ...

}

 

Listen() 메소드는 별도의 작업자 쓰레드가 실행하는 메소드입니다.

 

즉, Listen() 메소드는 메인 쓰레드가 아닌 다른 쓰레드에서 실행됩니다.

 

그러므로,

 

Listen() 메소드의 코드는 별도의 작업자 쓰레드 상에서 실행되며,

 

메인 쓰레드에서 생성된 컨트롤에는 접근할 수 없습니다.

 

그렇지만,

 

           Invoke(ad, "서버시작");

메소드 호출을 통해, 간접적으로 메인 쓰레드의 컨트롤에 접근할 수 있습니다.

 

위의 문장은

 

           this.Invoke(ad, "서버시작");

다음과 같습니다.

 

여기서, this 참조는 Form 개체를 가리키는 것이지요.

 

별도의 쓰레드에서 메인 쓰레드의 컨트롤에 접근하려면,

 

Form 개체의 Invoke() 메소드를 호출하면 되는 구나~~

 

하고 알고 계시면 되겠습니다. 
posted by 방랑군 2012. 1. 6. 17:33

            // 서버를 실행하는 컴퓨터의 IP를 찾아 종점을 생성합니다.
            IPHostEntry localHostEntry = Dns.GetHostByName(Dns.GetHostName());
posted by 방랑군 2012. 1. 6. 16:40
1. Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net.Sockets;
using System.Net;

namespace NetworkServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Before Start");
            IPAddress address = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(address, 8010);

            //Console.WriteLine("Before Listener Start");
            listener.Start();

            //Console.WriteLine("Before Accept Socket");
            Socket socket = listener.AcceptSocket();

            ////Console.WriteLine("Before Receive");
            //byte[] myByte = new byte[256];
            //socket.Receive(myByte);

            //string willOut = System.Text.Encoding.Default.GetString(myByte);

            //// 보내기.
            //byte[] wiiSend = System.Text.Encoding.UTF8.GetBytes("Send To Client From Server");

            Encoding utf8 = Encoding.UTF8;
            while (true)
            { 
                // Receive
                byte[] myByte = new byte[256];
                socket.Receive(myByte);

                // Conversion
                string willOut = utf8.GetString(myByte);
                willOut = willOut.Replace("\0", string.Empty);
                Console.WriteLine("Client : " + willOut);

                // Send
                Console.Write("Server : ");
                string willSendString = Console.ReadLine();
                if (willSendString == "EXIT")
                {
                    break;
                }

                byte[] willSend = utf8.GetBytes(willSendString);
                socket.Send(willSend);
            }

            //Console.WriteLine("Before Close");
            socket.Close();
            listener.Stop();
        }
    }
}


2. Client 
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;

namespace NetworkClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Before Connect");
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("127.0.0.1", 8010);
            Stream stream = tcpClient.GetStream();

            ////Console.WriteLine("Before Get Stream");
            //byte[] myByte = new byte[256];
            //string strLetters = "HWANG SEUNG JAE";
            //myByte = System.Text.Encoding.Default.GetBytes(strLetters);
            //Stream stream = tcpClient.GetStream();

            ////Console.WriteLine("Before Write");
            //stream.Write(myByte, 0, myByte.Length);


            ////받기
            //byte[] willOut = new byte[256];
            //stream.Read(willOut, 0, 256);
            Encoding utf8 = Encoding.UTF8;
            while (true)
            { 
                // Send
                Console.Write("Client : ");
                string myString = Console.ReadLine();
                if (myString == "EXIT")
                {
                    break;
                }

                byte[] myByte = utf8.GetBytes(myString);
                stream.Write(myByte, 0, myByte.Length);

                // Receive
                byte[] willOut = new byte[256];
                stream.Read(willOut, 0, 256);
                string willOutString = utf8.GetString(willOut);
                willOutString = willOutString.Replace("\0", string.Empty);
                Console.WriteLine("Server : " + willOutString);
            }

            //Console.WriteLine("Before Close");
            tcpClient.Close();
        }
    }
}
 
posted by 방랑군 2012. 1. 6. 15:48

1. Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net.Sockets;
using System.Net;

namespace NetworkServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before Start");
            IPAddress address = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(address, 8010);

            Console.WriteLine("Before Listener Start");
            listener.Start();

            Console.WriteLine("Before Accept Socket");
            Socket socket = listener.AcceptSocket();

            Console.WriteLine("Before Receive");
            byte[] myByte = new byte[256];
            socket.Receive(myByte);

            string willOut = System.Text.Encoding.Default.GetString(myByte); 

            Console.WriteLine("Before Close");
            socket.Close();
            listener.Stop();
        }
    }
}


2. Client 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;

namespace NetworkClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before Connect");
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("127.0.0.1", 8010);

            Console.WriteLine("Before Get Stream");
            byte[] myByte = new byte[256];
            string strLetters = "HWANG SEUNG JAE";
            //인터넷상에서 스트림 이동은 모두 바이트만 가능합니다. 
            myByte = System.Text.Encoding.Default.GetBytes(strLetters);
            Stream stream = tcpClient.GetStream();

            Console.WriteLine("Before Write");
            stream.Write(myByte, 0, myByte.Length);

            Console.WriteLine("Before Close");
            tcpClient.Close();
        }
    }
}
 
posted by 방랑군 2012. 1. 6. 15:36

출처 :  http://blog.naver.com/lcsco?Redirect=Log&logNo=120136771146 

String -> byte[] 로 변환하는 방법

 

String str = "string test data " ;

byte[] result = System.Text.Encoding.Default.GetBytes( str );

 

 

- byte[] -> String   로 변환하는 방법

byte[]  byte1 = System.Text.Encoding.Default.GetBytes( "byte test data" );

String result = System.Text.Encoding.Default.GetString( byte1 );


 

ps) 상황에 따라 엔코딩 방벙에는 Default, Unicode, UTF8, UTF16, UTF32등으로 사용 할 수 있다 .