c언어 소켓부분 질문드립니다!!

떼찌할꼬야의 이미지

WIN API 소켓부분을 실습을 하는데 답답한 부분이 있어서 질문올려드립니다.

일단 프로그램 내용은 클라이언트에서 argv로 이름을 입력하면 서버쪽에서는 그 이름의 학점을 전송해주는 프로그램입니다.

클라이언트 쪽에서 이름을 보내는 건 문제가 없는데 서버쪽에서 학점을 보낼 때, A,B 이런식으로 print가 안되고, 이상한 문자가 print되서 질문올려

드립니다.

소스는 다음과 같습니다.

혹시, string char 형식의 텍스트 파일 데이터를 각각의 array에 저장하고 싶은데, 이것도 잘 안되는 부분이라서.. 어떤 방법이 괜찮을지

아시는 분 계시면 답변 부탁드립니다..

#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <tchar.h>
 
 
#define nameSize 5
#define BUFSIZE 5
#define BUF_SIZE 1024
 
//server는 txt파일을 읽고, 배열에 저장하고, 요청하는 이름에 대해 학점을 출력해야 한다.
int main(int argc, char* argv[])
{
	int i=0;  //for문 돌리기 위한 counter
	char* name[5]; //name array
	char* score[5];  // score array
	struct sockaddr_in srvSAddr; //서버 구조체 듣기위한 소켓
	struct sockaddr_in connectAddr; // 통신하기 위한 소켓 구조체
	DWORD addrLen; 
	WSADATA wsa; //윈도우 소켓 비동기식 구조체
	DWORD servVal;
	SOCKET srvSock, sockio; //듣기위한 소켓과 통신하기 위한 소켓
	char sendScore[BUF_SIZE+5];
	char reqName[BUF_SIZE+5]; //clinet가 보낸 이름 저장소 
	int temp; //배열에서 search할 때 사용 
 
	FILE *fr;
	char torken;
	LPSTR TEMP;
 
 
 
	WSAStartup(MAKEWORD(2,0), &wsa); //원속 초기화
 
 
	//파일을 연다.
	fr= fopen(argv[1], "r");
 
	if(!fr)
	{
		printf("File open error!\n");
 
		return 0;
	}
 
	//배열들을 초기화
	for(i=0; i<nameSize; i++)
	{
		name[i] = "empty";
		score[i] = "F";
	}
 
	//파일로부터 읽어들임.
 
	/*while((torken = fgetc(fr)) != EOF)
    {
        if((torken >= 'a' && torken <= 'z') || (torken >= 'A' && torken <= 'Z'))
			strcat(name[i], (char*)torken);
 
		else if(torken == ' ')
		{			
			torken = fgetc(fr);
			score[i] = (char*)torken;
			torken = fgetc(fr);
			i++;
		}		
    }*/
 
 
	//임시 배열 초기화
	name[0] = "kim";
	name[1] = "choi";
	name[2] = "park";
	name[3] = "lee";
	name[4] = "jang";
 
	score[0] = "A";
	score[1] = "B";
	score[2] = "A";
	score[3] = "B";
	score[4] = "A"; 
 
 
 
	for(i=0; i<nameSize; i++)
		printf("%s %s\n", name[i], score[i]);
 
 
	//서버 구조체 초기화
	srvSock = socket(AF_INET, SOCK_STREAM, 0);  
 
	memset( &srvSAddr, 0, sizeof(srvSAddr));
	srvSAddr.sin_family = AF_INET;
	srvSAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	srvSAddr.sin_port = htons(50000);
 
	//소켓 바인드
	servVal = bind(srvSock, (struct sockaddr*) &srvSAddr, sizeof srvSAddr);
 
 
	//리슨하기 위해 준비
	servVal = listen(srvSock, 5);
 
 
	while(1)
	{
 
		//클라이언트 주소크기를 설정
		addrLen = sizeof(connectAddr);
 
		//accept가 있는지 기다린다.
		sockio = accept(srvSock, (struct sockaddr*) &connectAddr, &addrLen);
 
		//recv를 받는다. 
		servVal = recv(sockio, reqName, BUF_SIZE, 0);
 
		printf("receive : %s\n", reqName);
 
		//학점을 send해 준다.
		temp = 0;
 
		for(i=0; i<nameSize; i++)
			if(!strcmp(reqName, name[i]))  //이름 검색 후 학점을 찾아줌.
				temp = i;
 
		//이름을 배열에 없으면 x를 보내고, 있으면 학점을 보낸다.
		if(temp == 0)
			*sendScore = "이름이 존재하지 않습니다.";
		else
			*sendScore = score[i];
 
		servVal = send(sockio, sendScore, sizeof(sendScore)+1, 0);  
 
		TEMP = (LPSTR)sendScore;
		printf("보낸학점 : %s\n", TEMP);
	}
 
 
 
	shutdown(sockio, SD_BOTH);
	closesocket(sockio);
	servVal = WSACleanup();
 
	fclose(fr);
 
	return 0;
 
}
라스코니의 이미지

char sendScore[BUF_SIZE+5];

이렇게 선언되어 있는데, 아래 같이 하면 제대로 동작하지 않을 것 같네요

//이름을 배열에 없으면 x를 보내고, 있으면 학점을 보낸다.
if(temp == 0)
*sendScore = "이름이 존재하지 않습니다.";
else
*sendScore = score[i];

아래 처럼 하면

if(temp == 0)
strcpy(sendScore, "이름이 존재하지 않습니다.");
else {
sendScore[0] = score[i];
sendScore[1] = '\0';
}

servVal = send(sockio, sendScore, strlen(sendScore)+1, 0);

될 것 같기도 하네요.

떼찌할꼬야의 이미지

temp가 0일 때는 잘 되는데 else는 아직도 이상한 문자로 나오네요;; 유니코드 문제는 아닌가요? 윈도우 cmd창에서 실행하고 있는데..

----------------------------------------------------------------------
세상은 나와 내가 아닌 사람들이 살아가는 곳!!

라스코니의 이미지

char* score[5]; // score array
이었군요.

그럼 else 부분은
strcpy(sendScore, score[i]);
되어야 겠네요.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.