자바 질문도 괜찮죠? ^^*

은빛연어의 이미지

	public void run() {
		String data = "";
//System.out.println("0");
		while(connect_flag) {
			data = "";
			try {
System.out.println("1");
				data = dis.readUTF() + '\n';
System.out.println("2");
			} catch(IOException e) {
				memo.append("# read error");
			}
			
			memo.append(data);
		}
	}

위 코드처럼 //System.out.println("0");으로하면 "1"과 "2"가 안찍히네요...
근데 //를 빼면 "1"과 "2"가 찍혀요.. ㅡ,.ㅡ
당췌 자바를 모르는 지라서 어캐 손을 봐야되는지 모르겠네요... 조언좀 부탁해요 ^^;
sorcerer의 이미지

출력할 메시지를 출력한 후에 System.out.flush(); 를 넣어보세요.
전체 소스가 없으니 나머지는 모르겠네요.

SOrCErEr

은빛연어의 이미지

예전에 인터넷에 돌아다니는 네트웍프로그래밍 소스중에서 자바좀 공부할려구 하는데 잘 안되네염.. ^^ 전체 소스는 다음과 같습니다..

// 파일명: JavaChatClient.java
// 기  능: 자바 소켓을 이용한 채팅 클라이언트
// 컴파일: javac JavaChatClient.java
// 사용법: appletviewer JavaChatClient.html

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

//public class JavaChatClient extends Applet implements Runnable {
public class chat extends Applet implements Runnable {
	final int PORT = 8080;
	Thread readMessage = null;		// 수신 메시지를 읽는 스레드 선언
	
	Socket s;
	DataInputStream dis;
	DataOutputStream dos;
	Button connect, disconnect;		// 연결, 종료 버튼
	TextArea memo;				// 출력창
	TextField name;				// 참가자 이름 입력 창
	TextField field;			// 채팅 메시지 입력 창
	boolean connect_flag = false;		// 서버와의 연결 상태 플래그
	
	// 애플릿의 init() 메소드
	public void init() {

		// 이름 입력창, 연결 및 탈퇴 버튼
		Panel p = new Panel();
		Label label = new Label("My Name:");
		name = new TextField("noname");
		connect = new Button("Connect");
		connect.addActionListener(new ConnectListener());
		disconnect = new Button("Disconnect");
		disconnect.addActionListener(new DisconnectListener());
		p.add(label);
		p.add(name);
		p.add(connect);
		p.add(disconnect);
		
		// 메시지 입출력 창
		memo = new TextArea();
		memo.setEditable(false);			
		field = new TextField();
		field.addActionListener(new SendListener());
		
		setLayout(new BorderLayout());
		add(p, BorderLayout.NORTH);
		add(memo, BorderLayout.CENTER);
		add(field, BorderLayout.SOUTH);
	}
	
	// 연결(Connect) 버튼 처리 리스너
	class ConnectListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			if(connect_flag == false) {
				try {
					s = new Socket(getCodeBase().getHost(), PORT);
					dis = new DataInputStream(new
						 BufferedInputStream(s.getInputStream()));
					dos = new DataOutputStream(new
						 BufferedOutputStream(s.getOutputStream()));
				} catch(IOException e) {
					memo.append("# Can't open Socket\n");
					return;
				}
				memo.append("# Connected successfully! \n");
				
				// 통신을 담당할 스레드 생성
				makeReadMessageThread();
				readMessage.start();
				
				// 자신의 초기 정보를 서버에 전송
				try {
					dos.writeUTF(name.getText()+": has connected..");
					dos.flush();
				} catch(IOException e) {	
					memo.append("# Connection error\n");
 				}
				connect_flag = true;
			} else {
				// 중복 연결 시도 처리
				memo.append("# You are already connected\n");		
			}
		}
	}
		
	void makeReadMessageThread() {
			readMessage = new Thread(this);
	}
	
	// 스레드 실행 내용 (채팅 메시지를 읽어 화면에 출력)
	public void run() {
		String data = "";
//System.out.println("0");
		while(connect_flag) {
			data = "";
			try {
System.out.println("1");
				data = dis.readUTF() + '\n';
System.out.println("2");
			} catch(IOException e) {
				memo.append("# read error");
			}
			
			memo.append(data);
		}
	}

	// 채팅 메시지 송신 처리 리스너
	class SendListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			String msg = "["+name.getText()+"] "+ field.getText();
			try {
				dos.writeUTF(msg);
				dos.flush();
			} catch(IOException e) {
				memo.append("# Sending error\n");
			}
			field.setText("");
		}
	}
	// 종료(Disconnect) 버튼 처리 리스너
	class DisconnectListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			connect_flag = false;
			try {
				dos.writeUTF(name.getText()+": BYE...");
				dos.flush();
			} catch(IOException e) { }
			try {
				dos.close();
				dis.close();
				s.close();
			} catch(IOException e) { }
		}
	}
}

중간쯤에 보면 "// 스레드 실행 내용 (채팅 메시지를 읽어 화면에 출력) "이부분이 잘안되네염...
컴파일해서 수행해보면 상태가 질문처럼 되구요.. ^^;

은빛연어의 이미지

문제는 시간차였군요.. ^^;

서버에 connection요청을 한 후에, 수락되면 쓰레드 띄우고 이거저거 다 한 후에 connect_flag = true;를 하는데 이게 문제였군요..ㅋㅋ
시간차때문에 public void run() 에서 connect_flag가 false가 되어 있더군요.. ㅋㅋ

connection요청후에 바로 connect_flag = true;로 하니까 잘 되네염..
모두 감샤~

댓글 달기

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