방금 소켓 프로그래밍을 시작했고 Java의 Echo 서버에서 작업하고 있습니다. 내가하고자하는 일 중 하나는 TCP와 UDP 모두에서 서버를 구현하는 것이며 클라이언트은 런타임에 사용할 프로토콜을 선택할 수 있습니다..Java Echo Server TCP * 및 * UDP 구현?
이것은 멍청한 질문이지만, 사용자에게이 옵션을 허용하려면 TCP 또는 UDP 프로토콜을 선택 하시겠습니까? 스캐너 입력에서 프로토콜 선택을 분기하는 시작 부분에 if-else를 넣으려고 시도했지만 선택과 상관없이 두 블록을 건너 뛰었습니까?
감사합니다.
나는 TCP 에코 서버 구현했습니다:
public class EchoServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10007);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String cAddress = "";
String inputLine;
cAddress = clientSocket.getInetAddress().toString();
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine + " " + cAddress + " ");
out.println(inputLine + " " + cAddress);
if (inputLine.equals("bye"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
그리고 클라이언트 측을 다음을 사용하지 않고 자바에서 조건문을 할 수있는 방법은 (내가 아는)이 없다
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class EchoClient {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String serverHostname;
System.out.println("Enter an IP value: ");
serverHostname = s.next();
//String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
http://stackoverflow.com/questions/2819274/listening-for-tcp-and-udp-requests-on-the-same-port –
이것은 너무 광범위하여 여기에서 답변 할 수 없습니다 (' FAQ에있는 책을 쓰려면 "을 참조하십시오. –
문제가 클라이언트 코드와 관련된 경우 서버 코드를 알려주십시오. –