본문 바로가기

Ethernet Chat Server/아두이노와 윈도우 채팅 프로그램

채팅 프로그램 제작 전 : 아두이노 채팅 프로그램(Server)

안녕하세요.

Edward AHN입니다.

이번 시간은 Arduino Chat Program을 분석해보는 시간입니다.
최종 목표인 W5500-EVB로 채팅프로그램을 만들기 위해서 먼저, 아두이노의 기본 예제에 나와있는 채팅 프로그램을 보고 어떻게 채팅프로그램을 만들지에 대한 흐름을 이해를 하는 시간이 되겠습니다.
아래의 Code의 각 주석에는 Comment들이 있고, 제가 작성한 순서도가 있으니 참조하여 채팅프로그램을 어떠한 형식으로 만들어야겠구나. 라는 것을 인지하시기 바랍니다.

[code language="cpp"]
/*
Chat Server

A simple server that distributes any incoming messages to all
connected clients. To use telnet to your device's IP address and type.
You can see the client's input in the serial monitor as well.
Using an Arduino Wiznet Ethernet shield.

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)

created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

*/

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED // MAC Address declare
};
IPAddress ip(192, 168, 1, 177); // IP Address declare
IPAddress gateway(192, 168, 1, 1); // Gateway declare
IPAddress subnet(255, 255, 0, 0); // subnet mask declare
// telnet defaults to port 23
EthernetServer server(23); // Server Port is 23
boolean alreadyConnected = false; // whether or not the client was connected previously

void setup() { //initial start
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for port to open:
Serial.begin(9600); // Serial Comunication is 9600 Buad rate
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Chat server address:"); // Serial output
Serial.println(Ethernet.localIP()); // Serial output
}

void loop() {
// wait for a new client:
EthernetClient client = server.available();

// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clead out the input buffer:
client.flush(); // buffer clear
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
}

if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
}[/code]

Arduino chat server 순서도입니다.

순서도와 코드를 비교하시면서 보시면 이해하기 쉬울겁니다.

만약, 틀린 부분이 있거나 질문이 있으신분들은 댓글을 남겨주세요.

제목 없음