java Socket 编程

本文深入讲解Java中的Socket编程,包括单线程和多线程环境下客户端与服务器端的通信过程,涉及Socket、ServerSocket类的使用,以及输入输出流的处理。

socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。Socket和ServerSocket类库位于java.net包中。

ServerSocket用于服务器端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完成所需的会话。对于一个网络连接来说,套接字是平等的,并没有差别,不因为在服务器端或在客户端而产生不同级别。不管是Socket还是ServerSocket它们的工作都是通过SocketImpl类及其子类完成的。

对于ServerSocket应用于服务器端,通过构造器ServerSocket(int port)来创建绑定到特定端口的服务器套接字,下面介绍最重要的方法:accept():侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞,一旦有客户连接到服务器,就会通过这个方法返回一个Socket对象。
在C/S通过socket进行通信时,有两个比较重要的方法:getInputStream和getOutputStream;getInputStream返回此套接字的输入流,getOutputStream返回一个输出流,一般服务器监听客户线程接入后,获取客户请求输入,进行判断,然后做出相应的输出响应。下面来通过一个例子来详细说明:这里是单次单线程的通信,通信完成后客户端和服务器端都关闭了。

(1)客户端和服务器端进行字符串通信,当客户端发送”byebye”时,结束这次通信;
这里是服务器端代码:

public class ServerCode {
	// 设置端口号
	public static int portNo = 3333;
	
	public static void main(String[] args) throws IOException  {
		ServerSocket s = new ServerSocket(portNo);
		System.out.println("The Server is start: " + s);
		// 阻塞,直到有客户端连接
		Socket socket = s.accept();
		try {
			System.out.println("Accept the Client: " + socket);                   
			//设置IO句柄
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 
			while (true) {
				String str = in.readLine();
				if (str.equals("byebye")) {
					break;
				}
				System.out.println("In Server reveived the info: " + str);
				out.println(str);
			}
		} finally {
			System.out.println("close the Server socket and the io.");
			socket.close();
			s.close();
		}
	}
}

服务器端监听通过ServerSocket(portNo)来监听1024端口的接入,通过s.accept阻塞监听,首先设置InputSteam,通过InputStreamReader和BufferedReader的两层装饰,获得BufferedReader对象,因为BufferedReader有个readLine方法,可以读取一个文本行;再设置OutputStream,同样通过装饰获得PrintWriter对象,该对象有N多种格式化输出,方便使用;接着有一个while死循环,先读客户端输入,判断是不是”byebye”,如果是则跳出循环,否则输出响应信息,这里没做处理,直接返回客户上传的字符串。在finally里,关闭了socket和serversocket的对象。这就是服务器端的工作流程。

下面介绍客户端代码:

public class ClientCode {
	static String clientName = "Mike";
	//端口号
	public static int portNo = 1024;
	public static void main(String[] args) throws IOException{
 
		//要对应服务器端的1024端口号
		Socket socket = new Socket(“127.0.0.1”, portNo);
		try{
			System.out.println("socket = " + socket);
			// 设置IO句柄
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWrite out = new PrintWriter(BufferedWriter(newOutputStreamWriter(socket.getOutputStream())), true);
			out.println("Hello Server,I am " + clientName);
			String str = in.readLine();
			System.out.println(str);
			out.println("byebye");
		} finally {
			System.out.println("close the Client socket and the io.");
			socket.close();
		}
	}
}

客户端直接通过本地环回地址127.0.0.1加上portNo来连接服务器1024接口,和服务器端一样,设置了input和output流,这里和服务器端的处理是一样的,因为同样是socket操作,socket是不分服务器端和客户端的,他只是通信的一个工具而已,两边都要用的一个对象。

这里是交替执行的,客户端发消息,服务器收消息,服务器发消息,客户端收消息,客户端再发消息,这样循环下去,直到客户端想退出了,ClientCode代码里没有使用while循环,其实也完全可以用一个while循环来和服务器进行交流。

这里我也试了一下客户端向服务器请求文件的过程,也是可以的,只是把流换成了FileOutputStream和FileInputStream,由于做android的习惯,要求:不要在主线程里做太多耗时操作,重新开启一个线程进行下载:

public void setUpConn(RemoteFileClient rfc) {
		try {
			String savePath = new String("D:\\" + fileName);
			Socket client = new Socket(hostIp, hostPort);
			is = client.getInputStream();
			File file = new File(savePath);
			if (!file.exists()) {
				if (!file.createNewFile())
					throw new FileNotFoundException();
			}
			out = new PrintWriter((new OutputStreamWriter(client.getOutputStream())), true);
			out.println(fileName);
			Thread t = new Thread(new GetFile(is, new FileOutputStream(file), rfc));
			t.start();
			while(go) {
				try {
					System.out.println("Client is receiving...");
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (UnknownHostException e) {
			System.out .println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
		} catch (FileNotFoundException e) {
			System.out.println("File '" + fileName + "' not found");
		} catch (IOException e) {
			System.out.println("Error setting up socket connection: " + e);
		} finally {
			System.out.println("Receive full end");
		}
	}
class GetFile implements Runnable {
	
	public RemoteFileClient rfc;
	public InputStream is;
	public FileOutputStream out;
	public byte[] b;
	public GetFile(InputStream is, FileOutputStream out, RemoteFileClient rfc) {
		this.is = is;
		this.out = out;
		this.rfc = rfc;
		b = new byte[1024];
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println("Start to recive...");
			while(is.read(b) != -1) {
				out.write(b);
				out.flush();
			}
			System.out.println("Download complete...");
			out.close();//这里要记得关闭流
			rfc.closeConn();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

(2)再来介绍基于多线程的服务器代码,可以接受多个客户端连接,一个客户端也可以开启多个线程连接服务器端,打算下一步看看多线程下载,不知道多线程下载是不是通过设置每个线程下载偏移量来实现的,呵呵!只是猜测!下面来看代码,其实都差不多,只是开了个线程来实现而已,这里完成客户端请求服务器上D:\MOVIE下的文件:

public class ThreadServer {

	private int port;
	private ServerSocket server;

	public ThreadServer(int port) {
		this.port = port;
	}

	public void acceptConn() throws IOException{
		server = new ServerSocket(port);
		System.out.println("The Server is start: " + server);
		try {
			for (;;) {
				// 阻塞,直到有客户端连接
				Socket socket = server.accept();
				// 通过构造函数,启动线程
				new ServerThreadCode(socket);
			}
		} finally {
			server.close();
		}
	}
	
	public static void main(String[] args) throws IOException {

		// 服务器端的socket
		ThreadServer ts = new ThreadServer(1024);
		ts.acceptConn();
	}
}
public class ServerThreadCode extends Thread {
	// 客户端的socket
	private Socket socket;
	private BufferedReader in;
	private PrintStream out;

	// 默认的构造函数
	public ServerThreadCode() {
		// TODO Auto-generated constructor stub
	}

	public ServerThreadCode(Socket socket) throws IOException {
		this.socket = socket;
		// 初始化in和out的句柄
		System.out.println("Accept th client: " + socket);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintStream(socket.getOutputStream(), true);
		// 开启线程
		start();
	}

	// 线程执行的主体函数
	public void run() {
		byte[] b = new byte[1024];
			try {
				String name = in.readLine();
				FileInputStream fis = new FileInputStream(new File("D:\\movie\\" + name));
				while (true) {
					if (fis.read(b) != -1) {
						out.write(b, 0, 1024);
						out.flush();
						System.out.println("flush outing...");
					} else {
						out.close();
						in.close();
						fis.close();
						break;
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} 
}

这里只是在接受连接,阻塞结束后,开了一个线程来处理当前的socket连接,在ServerThreadCode构造器参数里,传进去一个Socket对象,ServerThreadCode实现了Runnable接口,其他操作和单线程里是一样的,客户端代码也都差不多,只是开启一个线程来去处理连接,连接里又开启一个线程去处理费时的下载:

class ClientThreadCode {
	
	public static void main (String[] args) {
		ExecutorService es = Executors.newFixedThreadPool(5);
		es.execute(new ThreadClient("127.0.0.1", 1024, "x.pdf"));
		es.execute(new ThreadClient("127.0.0.1", 1024, "xx.pdf"));
	}
}

主方法很简单,用ExecutorService来设置线程池大小,然后开启两个线程,分别下载x.pdf和xx.pdf,这里是同时下载的,实现多线程嘛,当然要同时!

public class ThreadClient extends Thread {
	
	private String hostIp;
	private int hostPort;
	public String fileName;
	
	public InputStream is;
	public PrintWriter out;
	
	public static boolean go = true;
	
	public static void setGo(boolean go) {
		ThreadClient.go = go;
	}
	
	public ThreadClient(String hostIp, int hostPort, String fileName) {
		this.hostIp = hostIp;
		this.hostPort = hostPort;
		this.fileName = fileName;
	}
	
	public void setFileName(String name) {
		this.fileName = name;
	}
	
	public void run() {
		try {
			String savePath = new String("D:\\" + fileName);
			Socket client = new Socket(hostIp, hostPort);
			is = client.getInputStream();
			File file = new File(savePath);
			if (!file.exists()) {
				if (!file.createNewFile())
					throw new FileNotFoundException();
			}
			out = new PrintWriter((new OutputStreamWriter(client.getOutputStream())), true);
			out.println(fileName);
			Thread t = new Thread(new GetFile(is, new FileOutputStream(file)));
			t.start();
			while(go) {
				try {
					System.out.println("Thread [" + this + "] Client is receiving...");
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			closeConn();
		} catch (UnknownHostException e) {
			System.out .println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
		} catch (FileNotFoundException e) {
			System.out.println("File '" + fileName + "' not found");
		} catch (IOException e) {
			System.out.println("Error setting up socket connection: " + e);
		} finally {
			System.out.println("Receive full end");
		}
	}
	
	public void closeConn() {
		try {
			out.println("byebye");
			out.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			System.out.println("all stream close...");
		}
	}
}

这是ThreadClient类代码,就是做了单线程里下载前的所有动作,那个GetFile类的实现和单线程里差不多,只是不需要传主的对象进去,之前主里做了回调关闭流和socket,这里主不做了:

class GetFile implements Runnable {
	
	public InputStream is;
	public FileOutputStream out;
	public byte[] b;
	
	public GetFile(InputStream is, FileOutputStream out) {
		this.is = is;
		this.out = out;
		b = new byte[1024];
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println("Start to recive...");
			while(is.read(b) != -1) {
				out.write(b);
				out.flush();
			}
			System.out.println("Download complete...");
			out.close();//这里要记得关闭流
			ThreadClient.setGo(false);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

这就是所有实现~~~

这还只是tcp下的,udp还没有看呢,还想看看http的实现,码农辛苦啊,知识太多了!

转载于:https://www.cnblogs.com/vtianyun/archive/2012/04/17/2453219.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值