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

java 网络编程

时间:2014-07-22 00:23:34      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:blog   java   os   io   re   c   

Server 端:

package foundation;

import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleSocketServer {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ServerSocket serverSocket = null;
		/*
		 * Socket socket = null; OutputStream os = null; InputStream is = null;
		 */
		// 监听端口号
//		Socket socket = null;
	/*	OutputStream os = null;
		InputStream is = null;*/
		int port = 10001;
		try {
			// 建立连接
			serverSocket = new ServerSocket(port);
			// 获得连接

			while (true) {
				
//				socket = 
				ExecutorService es = Executors.newCachedThreadPool();
				es.execute(new businessTask(serverSocket.accept()));

			}
			// 接收客户端发送内容

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流和连接
			/*	os.close();
				is.close();*/
//				socket.close();
				serverSocket.close();
			} catch (Exception e) {
			}
		}
	}
}

class businessTask implements Runnable {
	private Socket socket;
	private OutputStream os;
	private InputStream is;

	public businessTask(Socket socket) {
		this.socket = socket;
		
	}

	// 监听端口号
	int port = 10001;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			is = socket.getInputStream();
			byte[] b = new byte[1024];
			int n = is.read(b);
			// 输出
			System.out.println("客户端发送内容为:" + new String(b, 0, n));
			// 向客户端发送反馈内容
			os = socket.getOutputStream();
			os.write(b, 0, n);
			
			
			
				socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

  client端:

package foundation;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleSocketClient {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		Socket socket=null;
		
		InputStream is=null;
		OutputStream os=null;
		String serverIP="127.0.0.1";
		int port=10001;
		String data="hello";
		
		try {
			socket=new Socket(serverIP,port);
			
			os=socket.getOutputStream();
			os.write(data.getBytes());
			
			
			is=socket.getInputStream();
			byte[] b=new byte[1024];
			int n=is.read(b);
			System.out.println("server response:"+new String(b,0,n));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				os.close();
			
			is.close();
			socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

}

  

java 网络编程,布布扣,bubuko.com

java 网络编程

标签:blog   java   os   io   re   c   

原文地址:http://www.cnblogs.com/ericmeng/p/3858423.html

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