dictionaryserver.java

来自「一个java 在线字典程序 实现客户端在线查词」· Java 代码 · 共 82 行

JAVA
82
字号
import java.io.*;
import java.net.*;
import java.util.*;

public class DictionaryServer {

    public static void main(String[] args) throws IOException {

	DictionaryServer DiS = new DictionaryServer();
	String Meaning = null;
	String dictionary = args[0];
	ServerSocket DictServer = new ServerSocket(4500);
        System.out.println("Server is staring!");
	while (true) {
	    try
	    {
	    Socket SClient = DictServer.accept();
	    DataInputStream sinputstream = new DataInputStream(SClient
		    .getInputStream());
	    DataOutputStream soutputstream = new DataOutputStream(SClient
		    .getOutputStream());
	    String keyword = new String(sinputstream.readUTF());
	    Meaning = DiS.Dictionary(keyword, dictionary);
	    soutputstream.writeUTF(Meaning);

	    soutputstream.close();
	    soutputstream.close();
	    SClient.close();
	    }
	    catch(Exception e)
	    {
		
	    }
	}

    }

    public String Dictionary(String word, String inputfile) {
	Scanner inputStream = null;
	String keyword = word;
	String meaning = "no";
	try {
	    inputStream = new Scanner(new FileInputStream(inputfile));
	    String line = null;
	    while (inputStream.hasNextLine()) {
		line = inputStream.nextLine();
		try {
		    meaning = Check(keyword, line);
		} catch (Exception e) {
		    e.printStackTrace();
		    meaning = "no";
		}
		if (meaning.equals("no")) {
		    continue;
		} else {
		    return meaning;
		}
	    }
	} catch (FileNotFoundException e) {
	    System.out.println("Note: " + inputfile + " doesn't exist!");
	}
	
	return meaning;
    }

    public String Check(String word, String line) throws Exception {

	String mean = null;
	
	String delimiters = ":";
	StringTokenizer wordFactory = new StringTokenizer(line, delimiters);
	if (wordFactory.hasMoreTokens()) {
	    String newword = wordFactory.nextToken();
	     mean = wordFactory.nextToken();
	    if (newword != null && newword.equalsIgnoreCase(word)) {
		return mean;
	    }
	}
	return mean = "no";
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?