서버와 클라이언트로 간단한 프로그램을 만들고 텍스트 문자열을 앞뒤로 전달하려고합니다. 연결에 문제가 있습니다. 소켓 받아들이 기 라인 바로 아래에 테스트 인쇄 라인이 있으며 결코 인쇄되지 않으므로 문제가 있다고 가정합니다. 그러나 더 철저한 검사를 수행하는 방법을 모르겠습니다.Java에서 소켓 연결을 수락하지 못했습니다.
나는이 프로그램을 이클립스로 작성했다.
이 서버입니다 :
import java.io.*;
import java.net.*;
public class HW2Q1S {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
//data xfer
BufferedReader sIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter sOut = new PrintWriter(skt.getOutputStream(), true);
//string receiving
int count = 1;
String msg = "";
while((msg = sIn.readLine()) != null) {
while(count < 11) {
msg = sIn.readLine();
System.out.println("Received: "+ msg);
String returnMsg = msg.toUpperCase();
System.out.println("Capped: "+ returnMsg);
sOut.write(returnMsg);
count++;
}
} //end of read from client in while loop
if (count == 10) {
System.out.println("Max reached.");
}
srvr.close();
return;
}
catch(Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
그리고 이것은 클라이언트입니다 :
import java.util.Random;
import java.io.*;
import java.net.*;
public class HW2Q1C {
public static void main(String[] args) throws IOException {
String capped = "";
String temp = "";
try {
//make the connection
Socket skt = new Socket("localhost", 7654);
BufferedReader cIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter cOut = new PrintWriter(skt.getOutputStream(), true);
//send 11 strings
for (int i = 0; i < 11; i++) {
temp = Stringer();
cOut.write(temp);
System.out.println("Sending: " + temp);
}
//receive server strings
while(cIn.readLine() != null) {
capped = cIn.readLine();
System.out.println("From server: "+ capped);
}
skt.close();
} // end of connection try block
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
감사합니다!
예외가 발생했을 것으로 추측합니다. 스택 추적은 무엇입니까? 디버깅 해봤습니까? – Altoyyr
그것이 내가 생각한 것이지만 콘솔에는 아무것도 없다. 그것은 완전히 비어 있습니다. – TurtleOrRodeo
난 방금 당신의 프로그램을 실행하고 내가 볼 수있는 한 연결 자체는 괜찮습니다. srvr.accept()는 클라이언트가 연결될 때까지 기다립니다 (제대로 수행함). 이것은 도움이 될 것입니다. http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html – Altoyyr