我刚刚开始进行套接字编程,并且正在使用 Java 开发 Echo 服务器。我想做的一件事是在 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();
}
}