简介
套接字最初叫伯克利套接字,因为是由伯克利大学最初发明的。在Java中,可以很方便地调用Socket进行网络通信。下面,就试着用套接字向远程服务器进行读写数据。
代码演示
package demo0811.demo1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
/**
* 应用套接字进行单词含义查询
* @author zzw
*
*/
public class DictionaryClient {
private Socket socket=null;
private static final int TIMEOUT=20000;
private static final String SERVER="dict.org";
private static final int PORT=2628;
public DictionaryClient(String[] words) throws Exception {
socket=new Socket(SERVER,PORT);
socket.setSoTimeout(TIMEOUT);
OutputStream outputStream = socket.getOutputStream();
Writer outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter=new BufferedWriter(outputStreamWriter);
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
for(String word:words)
define(word,outputStreamWriter,bufferedReader);
}
private static void define(String word,Writer writer,BufferedReader reader) {
try {
writer.write("DEFINE eng-lat "+word+"\r\n");
writer.flush();
for(String line=reader.readLine();line!=null;line=reader.readLine()) {
if(line.startsWith("250")) {
return;
} else if (line.startsWith("552")) {
System.out.println("No definition for "+word);
return;
} else if(line.matches("\\d\\d\\d .*")) {
continue;
} else if(line.trim().equals(".")) {
continue;
} else {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试代码
package demo0811.demo1;
public class Test {
public static void main(String[] args) throws Exception {
String[] words={"you","computer","sky"};
new DictionaryClient(words);
}
}