码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-08-11 12:25:19      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

简介

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

}




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

标签:

原文地址:http://my.oschina.net/zzw922cn/blog/490645

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!