我基本上尝试使用套接字创建一个简单的域解析器。
我很远,我现在正在努力。除了我的主要功能,我尝试制作一个线程,它一直在监听并等待另一个电话。输入www.google.com后,它会给我一个地址,但是当我再次尝试时,它什么也没做。我认为套接字关闭或什么的。我想使用线程和while
循环,但我在这个问题上挣扎了几个小时。
客户端( EchoClient.java )
package tetst222;
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
try
{
Socket sock = new Socket("localhost", 1350);
PrintWriter printout = new PrintWriter(sock.getOutputStream(),true);
InputStream in = sock.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bin.readLine()) != null)
{
System.out.println(line);
}
//sock.close();
}
catch(IOException ioe)
{
System.err.println(ioe);
}
}
}
这段代码:
服务器端( EchoServer.java )
package tetst222;
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class EchoServer //implements Runnable
{
public static void main(String[] args) throws IOException
{
try
{
ServerSocket sock = new ServerSocket(1350);
while(true)
{
// open socket
Socket client = sock.accept();
PrintWriter printout = new PrintWriter(client.getOutputStream(),true);
printout.println("Je bent succesvol verbonden met de host");
printout.println("Geef een hostnaam op waarvan je het IP-adres wilt achterhalen:");
//get input from client
InputStream in = client.getInputStream();
BufferedReader bufin = new BufferedReader(new InputStreamReader(System.in));
/*
Thread t = new Thread();
t.start();
*/
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
client.close();
}
}catch(IOException ioe)
{
System.err.println(ioe);
}
}
/*
public void run() {
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
host = sc.nextLine();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}catch (IOException e) {
System.err.println("IOException: " + e);
}
}
*/
}
答案 0 :(得分:1)
您的服务器无法处理客户端请求。它等待新客户端(socket.accept)并读取默认系统输入(System.in)而不是套接字,并且在关闭客户端连接之后。
它看起来像是:public static void main(String[] args) throws IOException {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Typ de host die u wilt resolven: ");
String host = sc.nextLine();
try {
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
} catch (UnknownHostException uhe) {
System.out.println(uhe.toString());
}
}
}
在客户端,您应该从控制台读取地址,将其写入套接字(发送请求),然后从套接字读取数据(接收响应)并输出到控制台;
在服务器端,您必须接受客户端连接(socket.accept),从套接字读取数据(接受请求),处理它(InetAddress.getByName(host))并将响应发送回客户端套接字。