Java套接字编程向服务器进行读写数据

简介

套接字最初叫伯克利套接字,因为是由伯克利大学最初发明的。在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);
	}

}




转载于:https://my.oschina.net/zzw922cn/blog/490645

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值