수다닷컴

  • 해외여행
    • 괌
    • 태국
    • 유럽
    • 일본
    • 필리핀
    • 미국
    • 중국
    • 기타여행
    • 싱가폴
  • 건강
    • 다이어트
    • 당뇨
    • 헬스
    • 건강음식
    • 건강기타
  • 컴퓨터
    • 프로그램 개발일반
    • C언어
    • 비주얼베이직
  • 결혼생활
    • 출산/육아
    • 결혼준비
    • 엄마이야기방
  • 일상생활
    • 면접
    • 취업
    • 진로선택
  • 교육
    • 교육일반
    • 아이교육
    • 토익
    • 해외연수
    • 영어
  • 취미생활
    • 음악
    • 자전거
    • 수영
    • 바이크
    • 축구
  • 기타
    • 강아지
    • 제주도여행
    • 국내여행
    • 기타일상
    • 애플
    • 휴대폰관련
  • 프로그램 개발일반
  • C언어
  • 비주얼베이직

자바 쓰레드 관련 서버&클라이언트 통신

냐하

2023.04.01


*handler 소스
import java.io.*;
import java.net.*;
import java.util.*;
public class handler extends thread
{
protected static bufferedreader netin = null;
protected static printwriter netout = null;
protected static bufferedreader conin = null;
protected static printwriter conout = null;
protected static final string eor = end_of_response;
protected static file currentdir = null;
protected socket client;
public handler(string name)
{
super(name);
}

public synchronized void setsocket(socket client)
{
this.client = client;
notify();
}
public boolean isworking()
{
return (client != null);
}
public void run()
{
while(true)
{
synchronized(this)
{
try{
wait();
}catch(interruptedexception ie){}
}
try
{
netin = new bufferedreader(new inputstreamreader(client.getinputstream()));
netout = new printwriter(new outputstreamwriter(client.getoutputstream()));
conin = new bufferedreader(new inputstreamreader(system.in));
conout = new printwriter(new outputstreamwriter(system.out));
}
catch (ioexception ioe)
{
system.err.println(failed to get stream...);
system.exit(1);
}
netout.println(welcome to the filemanager server...);
netout.println(eor);
netout.flush();
currentdir = new file(system.getproperty(user.dir));
string cmdline;
while(true) {
try {
cmdline = netin.readline();
processcmd(cmdline);
} catch(ioexception ioe) {
system.err.println(exception in processing command...);
system.exit(1);
}
}
}
}
static void processcmd(string cmdline) {
if(cmdline == null) {
cmdbadcommand();
netout.println(eor);
netout.flush();
return;
}
stringtokenizer tokens = new stringtokenizer(cmdline.trim());
string cmd = null;
string arg1 = null;
string arg2 = null;
if(tokens.hasmoretokens()) {
cmd = tokens.nexttoken();
if(tokens.hasmoretokens()) {
arg1 = tokens.nexttoken();
}
if(tokens.hasmoretokens()) {
arg2 = tokens.nexttoken();
}
} else {
cmdbadcommand();
netout.println(eor);
netout.flush();
return;
}
if(cmd.equals(help)) {
cmdhelp();
} else if((cmd.equals(history)) ||cmd.equals(h)) {
cmdhistory();
} else if((cmd.equals(list)) ||cmd.equals(l)) {
cmdlist();
} else if((cmd.equals(rename)) ||cmd.equals(ren)) {
cmdrename(arg1, arg2);
} else if((cmd.equals(add)) ||cmd.equals(a)) {
cmdadd(arg1, arg2);
} else if((cmd.equals(sub)) ||cmd.equals(s)) {
cmdsub(arg1, arg2);
} else if((cmd.equals(mul)) ||cmd.equals(m)) {
cmdmul(arg1, arg2);
} else if((cmd.equals(div)) ||cmd.equals(d)) {
cmddiv(arg1, arg2);
} else if((cmd.equals(delete)) ||cmd.equals(del)) {
cmddelete(arg1);
} else if((cmd.equals(makedir)) ||cmd.equals(md)) {
cmdmakedir(arg1);
} else if((cmd.equals(changedir)) ||cmd.equals(cd)) {
cmdchangedir(arg1);
} else if((cmd.equals(find)) ||cmd.equals(f)) {
cmdfind(arg1);
} else if((cmd.equals(type)) ||cmd.equals(t)) {
cmdtype(arg1);
} else {
cmdbadcommand();
}
netout.println(eor);
netout.flush();
}
static void cmdhelp() {
netout.println(file manager command);
netout.println(---------------------------------- );
netout.println( help );
netout.println( * history(h) );
netout.println( list(l) );
netout.println( rename(ren) [old name] [new name] );
netout.println( * add(a) [data1] [data2] );
netout.println( * sub(s) [data1] [data2] );
netout.println( * mul(m) [data1] [data2] );
netout.println( * div(d) [data1] [data2] );
netout.println( find(f) [filename/dir name] );
netout.println( * type(t) [filename] );
netout.println( delete(del) [filename/dir name] );
netout.println( makedir(md) [dir name] );
netout.println( changedir(cd) [dir name] );
netout.println(---------------------------------- );
netout.flush();
}
static void cmdhistory() {
netout.println(---------------------------------- );
netout.println(my name is kong jin san);
netout.println(---------------------------------- );
netout.flush();
}
static void cmddelete(string arg) {
if(arg == null) {
cmdbadcommand();
return;
}
file file = new file(currentdir, arg);
if(file.delete()) {
netout.println(file + file.getname() + deleted... );
netout.flush();
} else {
netout.println(failed to delete file... );
netout.flush();
}
}
static void cmdrename(string arg1, string arg2) {
if((arg1 == null) || (arg2 == null)) {
cmdbadcommand();
return;
}
file file = new file(currentdir, arg1);
file target = new file(currentdir, arg2);
if(target.exists()) {
target.delete();
}
file.renameto(target);
netout.println(file + arg1 + - + arg2 );
netout.flush();
}
static void cmdadd(string arg1, string arg2) {
if((arg1 == null) || (arg2 == null)) {
cmdbadcommand();
return;
}
int d1, d2, answer;
d1 = integer.parseint(arg1);
d2 = integer.parseint(arg2);
answer = d1 + d2;
netout.println( d1 + + + d2 + = + answer);
netout.flush();
}
static void cmdsub(string arg1, string arg2) {
if((arg1 == null) || (arg2 == null)) {
cmdbadcommand();
return;
}
int d1, d2, answer;
d1 = integer.parseint(arg1);
d2 = integer.parseint(arg2);
answer = d1 - d2;
netout.println( d1 + - + d2 + = + answer);
netout.flush();
}
static void cmdmul(string arg1, string arg2) {
if((arg1 == null) || (arg2 == null)) {
cmdbadcommand();
return;
}
int d1, d2, answer;
d1 = integer.parseint(arg1);
d2 = integer.parseint(arg2);
answer = d1 * d2;
netout.println( d1 + x + d2 + = + answer);
netout.flush();
}
static void cmddiv(string arg1, string arg2) {
if((arg1 == null) || (arg2 == null)) {
cmdbadcommand();
return;
}
int d1, d2, answer;
d1 = integer.parseint(arg1);
d2 = integer.parseint(arg2);
answer = d1 / d2;
netout.println( d1 + / + d2 + = + answer);
netout.flush();
}
static void cmdlist() {
file[] list = currentdir.listfiles();
netout.println(file list in + currentdir.getname() );
netout.println(====ln(================================================== );
for(int i=0 ; ilist.length ; i++) {
if(list[i].isfile()) {
netout.println(list[i].getname() + \t\t + (list[i].canread()?r:_) + (list[i].canwrite()?w:_) + + list[i].length() + \t + (list[i].ishidden()?hidden:) );
netout.flush();
} else if(list[i].isdirectory()) {
netout.println([ + list[i].getname() + ]\t\t + (list[i].canread()?r:_) + (list[i].canwrite()?w:_) );
netout.flush();
}
}
netout.println(================================================== );
netout.println(total + list.length + items listed... );
netout.flush();
}
static void cmdtype(string arg) {
if(arg == null) {
cmdbadcommand();
return;
}
try{
filereader filein = new filereader(arg);
int c;
while ((c = filein.read()) != -1) {
netout.write((char) c);
}
netout.write(eor);
netout.flush();
netout.close();
} catch(ioexception ignored) {}
}
static void cmdmakedir(string arg) {
if(arg == null) {
cmdbadcommand();
return;
}
file dir = new file(currentdir, arg);
if(dir.exists()) {
// does nothing
} else {
dir.mkdir();
}
netout.println(directory + arg + constructed... );
netout.flush();
}
static void cmdchangedir(string arg) {
if(arg == null) {
cmdbadcommand();
return;
}
file newdir = new file(currentdir, arg);
if(!(newdir.exists()) || !(newdir.isdirectory())) {
netout.println(invalid directory... );
netout.flush();
} else {
currentdir = newdir;
netout.println(moved to + arg );
netout.flush();
}
}
static void cmdfind(string arg) {
if(arg == null) {
cmdbadcommand();
return;
}
file file = new file(arg);
if(file.exists()) {
netout.println(file + arg + exists...);
netout.flush();
} else {
netout.println(file + arg + not found);
netout.flush();
}
}
static void cmdbadcommand() {
netout.println(bad command...);
netout.flush();
}
static void getresponse() throws ioexception {
string line;
while(!((line = netin.readline()).equals(eor))) {
conout.println(line);
}
conout.flush();
}
}

*testserver3 소스
import java.io.*;
import java.net.*;
import java.util.*;
public class testserver3 {
public static void main(string[] args) {
system.out.println(file manager server program...);
serversocket server = null;
handler[] handlers = new handler[10];
for (int i = 0;i10 ;i++ )
{
handlers[i] = new handler(handler + i);
handlers[i].start();
}
try {
server = new serversocket(5264);
while(true)
{
socket client = server.accept();
int r;
do{
r=(int)(math.random()*10);
}while(handlers[r].isworking());
handlers[r].setsocket(client);
}
} catch(ioexception ioe) {
system.err.println(exception generated...);
}
finally
{
try{
server.close();
}catch(ioexception ignored){}
}
}
}
*testclient3 소스
import java.io.*;
import java.net.*;
import java.util.*;
public class testclient3
{
protected static bufferedreader netin = null;
protected static printwriter netout = null;
protected static bufferedreader conin = null;
protected static printwriter conout = null;
protected static final string eor = end_of_response;

public static void main(string[] args)
{
if(args.length 0) {
system.err.println(syntax: java testclient3+ [server address]);
system.exit(1);
}
if(args.length 0) {
fmclient(args[0]);
} else {
system.err.println(invalid command-line arguments);
system.exit(1);
}
}
static void fmclient(string addr) {
system.out.println(file manager client program...);
socket socket = null;
try {
socket = new socket(addr, 5264);
system.out.println(connected to... +
socket.getinetaddress().gethostname());
} catch(ioexception ioe) {
system.err.println(failed to connect to server...);
system.exit(1);
}
try {
netin = new bufferedreader(new inputstreamreader(socket.getinputstream()));
netout = new printwriter(new outputstreamwriter(socket.getoutputstream()));
conin = new bufferedreader(new inputstreamreader(system.in));
conout = new printwriter(new outputstreamwriter(system.out));
} catch(ioexception ioe) {
system.err.println(failed to get stream...);
system.exit(1);
}
try {
string line;
while( !(line = netin.readline()).equals(eor) ) {
conout.println(line);
conout.flush();
}
while(true) {
conout.print(command );
conout.flush();
line = conin.readline();
netout.println(line );
netout.flush();
getresponse();

conout.println();
conout.flush();
}
} catch(ioexception ioe) {
system.err.println(exception in communication...);
system.exit(1);
}
}
static void getresponse() throws ioexception {
string line;
while(!((line = netin.readline()).equals(eor))) {
conout.println(line);
}
conout.flush();
}
}testserver3을 실행시켜놓고
2~3개정도 testclient3를 localhost로 접속을 합니다.
접속을 하게된후에 명령어를 치면
예를 들어 첫번째클라이언트로 help를 치고,
다른 클라이언트에서는 histroy를 치게되면 한쪽 클라이언트는 먹통이되고
첫번째클라이언트에서 histroy정보가 뜹니다.
다중 쓰레드를 사용하여 코딩을 했는데...클라이언트가 두개이상되면 왜 명령어가 안먹히코 무한룹을 도는지
궁금합니다.....다른 오류는 없습니다...

testserver3을 실행시켜놓고
2~3개정도 testclient3를 localhost로 접속을 합니다.
접속을 하게된후에 명령어를 치면
예를 들어 첫번째클라이언트로 help를 치고,
다른 클라이언트에서는 histroy를 치게되면 한쪽 클라이언트는 먹통이되고
첫번째클라이언트에서 histroy정보가 뜹니다.
다중 쓰레드를 사용하여 코딩을 했는데...클라이언트가 두개이상되면 왜 명령어가 안먹히코 무한룹을 도는지
궁금합니다.....다른 오류는 없습니다...

신청하기





COMMENT

댓글을 입력해주세요. 비속어와 욕설은 삼가해주세요.

번호 제 목 글쓴이 날짜
2694921 보더 레이아웃 안에 플로우 레이아웃 넣는방법? 초롱 2025-05-15
2694894 웹 프로그래밍 관련해서 질문합니다. 창의적 2025-05-15
2694868 컨택트 폼 7에서 textarea 높이 조정 영글 2025-05-15
2694818 line-height값이 적용이 안되는데 왜 그런 거예요?. letter-spacing,line-height의 기준?? (2) 풍란 2025-05-14
2694795 이것 어떻게 좀 해결좀;; (3) 개럭시 2025-05-14
2694724 코딩시 폰트 문제; ㅠ 후력 2025-05-13
2694696 텍스트박스 입력에 관한 문제입니다. 딥공감 2025-05-13
2694668 [질문] 페이퍼비전 PointLight 관련 질문 드려요.. 두바다찬솔 2025-05-13
2694611 Flash Lite 2.1에서 BitmapData와 Matrix 지원안하나요? (3) 이플 2025-05-12
2694582 IE & 파이어폭스 (2) 흙이랑 2025-05-12
2694553 무비클립안의 duplicate 발동이 안돼네요; 딥보라 2025-05-12
2694523 자바 애플릿 질문좀 ^^ (6) 동이 2025-05-12
2694494 [질문] JAVA 또는 C++ 로 프로그램 개발시.. 레지스터리 등록 관련 의문점? (3) 우람늘 2025-05-11
2694469 익스6에서 css버그 나오는것 해결방법좀요 !!!! (6) 원술 2025-05-11
2694442 로컬에선 잘 나오는데 운영에 반영하면 이상하게 나와요. (8) 목화 2025-05-11
2694412 [질문] 이미지 로딩후 사이즈 조절할때 (1) 아담 2025-05-11
2694391 설치형 블로그 쓰시는 분들 어떤거 쓰세요?? (7) AngelsTears 2025-05-10
2694362 Microsoft SQL Server에서 서버만드는법 어둠 2025-05-10
2694333 for문으로 돌린 이름의 제어 (4) 레이 2025-05-10
2694308 이미지 css 도와주세요 ㅠㅠ (2) 애기 2025-05-10
<<  이전  1 2 3 4 5 6 7 8 9 10  다음  >>

수다닷컴 | 여러분과 함께하는 수다토크 커뮤니티 수다닷컴에 오신것을 환영합니다.
사업자등록번호 : 117-07-92748 상호 : 진달래여행사 대표자 : 명현재 서울시 강서구 방화동 890번지 푸르지오 107동 306호
copyright 2011 게시글 삭제 및 기타 문의 : clairacademy@naver.com