首页 > 其他 > 详细

socket简单小例子

时间:2014-12-23 02:19:40      阅读:286      评论:0      收藏:0      [点我收藏+]

Client

package socket;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
	public static void main(String[] args) {
		OutputStream output = null;
		BufferedWriter writer = null;
		Socket socket = null;
		try {
			//1.创建socket
			socket = new Socket("localhost",9999);
			//2.获取输出流
			output = socket.getOutputStream();
			//3.输出流包装成缓冲流
			writer = new BufferedWriter(new OutputStreamWriter(output));
			Scanner input = new Scanner(System.in);
			System.out.println("start input");
			//4.写入到输出流
			writer.write(input.next());
			//5.提交数据
			writer.flush();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				writer.close();
				output.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}

Server

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static void main(String[] args) {
		Socket socket = null;
		ServerSocket server = null;
		InputStream is = null;
		BufferedReader reader = null;
		try {
			//1.开启监听
			server = new ServerSocket(9999);
			System.out.println("start listener");
			//2.接受客户端传过来的信息
			socket = server.accept();
			//3.获取输入流
			is = socket.getInputStream();
			//4.输入流包装成缓冲流
			reader = new BufferedReader(new InputStreamReader(is));
			//5.读取打印
			System.out.println(reader.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
				reader.close();
				socket.close();
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

?

?

socket简单小例子

原文:http://chendaiming.iteye.com/blog/2169310

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!