tcp 서버 클라이언트

익명 사용자의 이미지

#pragma once
#pragma comment(lib, "ws2_32.lib")
 
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define PORT 8080
#define PACKET_SIZE 1024
 
#include <iostream>
#include <winsock2.h>
#include <windows.h>
#include <thread> //thread
#include <cstdlib> //strcpy_s
#include <string> //getline
#include <windows.h>
bool flag = 1;
 
void recvData(SOCKET& s) {
	char buffer[PACKET_SIZE];
	while (TRUE) {
		ZeroMemory(buffer, sizeof buffer);
		recv(s, buffer, sizeof buffer, 0);
		if (strcmp(buffer, "[exit]") == 0) {      // 서버를 정상종료, 클라이언트까지 모두 종료
			send(s, buffer, sizeof buffer, 0);
			std::cout << "[서버종료]\n";
			break;
		}
 
		if (strcmp(buffer, "[wait]") == 0) {     // 서버만 종료, 클라이언트는 대기상태
			std::cout << "[서버가 접속할때까지 대기]\n";
			flag = 0;
			break;
		}
 
		std::cout << "Server : " << buffer << std::endl;
	}
}
 
 
int main() {
	char IP[PACKET_SIZE] = { 0 },
		name[PACKET_SIZE] = { 0 },
		message[PACKET_SIZE] = { 0 };
 
	std::cout << "이름을 입력하세요 : ";
	std::cin >> name;
	std::cout << "아이피를 입력하세요 : "; // 로컬주소 127.0.0.1
	std::cin >> IP;
 
	while (TRUE) {
		std::cout << "접속대기중..";
		WSADATA wsa;
		WSAStartup(MAKEWORD(2, 2), &wsa);
 
		SOCKET server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 
		SOCKADDR_IN addr = { 0 };
		addr.sin_addr.s_addr = inet_addr(IP);
		addr.sin_port = PORT;
		addr.sin_family = AF_INET;
 
		while (connect(server, (SOCKADDR*)&addr, sizeof addr));
		flag = 1;
		std::cout << "서버와 연결되었습니다.\n";
		send(server, name, sizeof name, 0);
 
		std::thread(recvData, std::ref(server)).detach();
 
		while (flag) {
			ZeroMemory(message, sizeof message);
			std::cout << "메세지를 입력하세요: ";
			std::cin >> message;
			send(server, message, sizeof message, 0);
		}
	}
}

#pragma once
#pragma comment(lib, "ws2_32.lib") //링커
 
#define PORT 8080 
#define PACKET_SIZE 1024
 
#include <iostream> // c++ stadard input output
#include <winsock2.h> // winsock
#include <windows.h> // ZeroMemory
#include <vector> //vector
#include <utility> //pair
#include <thread> //thread
#include <cstdlib>
 
class CLIENT {
public:
	SOCKET client;
	SOCKADDR_IN clientaddr = { 0 };
	int clientsize = sizeof clientaddr;
	int number = -1;
	CLIENT() { }
};
 
typedef std::pair<CLIENT, std::string> pii;
 
std::vector<pii> Client;
 
void recvData(SOCKET s, int num) { 
	char buffer[PACKET_SIZE] = { 0 };
	recv(s, buffer, sizeof buffer, 0);
	Client[num].second = buffer;
 
	while (TRUE) {
		ZeroMemory(buffer, sizeof buffer);
		recv(s, buffer, sizeof buffer, 0);
 
		if (strcmp(buffer, "[exit]") == 0) {
			send(s, buffer, sizeof buffer, 0);
			std::cout << "[서버종료]\n";
			break;
		}
 
		if (strcmp(buffer, "[wait]") == 0) {
			send(s, buffer, sizeof buffer, 0);
			std::cout << "[서버대기]\n";
		}
		std::cout << Client[num].second << " : " << buffer << std::endl;
	}
}
 
void ACCEPT(SOCKET &s) { 
	int cnt = 0;
	while (TRUE) {
		Client.push_back(pii(CLIENT(), ""));
		Client[cnt].first.client = accept(s, (SOCKADDR*)&Client[cnt].first.clientaddr, &Client[cnt].first.clientsize);
		Client[cnt].first.number = cnt;
		std::thread(recvData, Client[cnt].first.client, cnt).detach();
		cnt += 1;
	}
}
 
 
 
int main() {
	WSADATA wsa;
	WSAStartup(MAKEWORD(2,2), &wsa);
 
	SOCKET server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 
	SOCKADDR_IN addr = { 0 };
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = PORT;
	addr.sin_family = AF_INET;
 
	bind(server, (SOCKADDR*)&addr, sizeof addr);
	listen(server, SOMAXCONN);
 
	std::thread(ACCEPT, std::ref(server)).detach();
 
	char name[PACKET_SIZE],
		message[PACKET_SIZE];
 
	while (TRUE) {
		ZeroMemory(message, sizeof message);
		std::cin >> message;
 
		for (int i = 0; i < Client.size(); i++)
			send(Client[i].first.client, message, sizeof message, 0);
	}
}

tcp 서버와 클라이언트 간단한 채팅 코드인데
서버가 [wait]을 입력하면 클라이언트가 대기하면서 서버가 접속할때까지 기다리도록 하고싶습니다.
서버가 다시 켜지면 자동으로 클라이언트와 접속되도록 하고싶은데
쓰레드를 이용해서 메시지를 받는것과 보내는 것을 나눠두었고 while문에서 계속 메시지를 입력하도록 해야하는데 다시 연결이 되려면 메시지를 입력하는 while문에서 벗어나기 위해 flag를 사용하였습니다. 하지만 이미 cin으로 메시지를 받기위해 기다리고있기 때문에 채팅에서 한번은 메시지를 입력해야지 대기상태로 넘어갈 수 있습니다. 이를 해결하기 위한 방법이 없을까요?

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.