Dowemo
0 0 0 0

Introduction to socket
socket起源于Unix,而Unix/Linux基本哲学之一就是"一切皆文件",都可以用"打开open -> 读写write/read -> 关闭close"模式来操作。我的理解就是Socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭),这些函数我们在后面进行介绍。
Java implementation

Project structure

这里写图片描述

Socket server

package com.taowd.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;/**
 * 功能:Socket服务端
 * @author Taowd
 *
 */public class SocketServices {
 public static void main(String[] args) {
 try {
//1、创建ServiceSocket,开启监听端口8888 ServerSocket serviceSocket = new ServerSocket(8888); System.out.println("******服务端启动,正在监听8888端口******"); Socket socket = serviceSocket.accept();//开启监听//获取一个输入流,接收客户端发送的数据
 System.out.println("开始接受客户端数据----"); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String temp = ""; while ((temp = br.readLine())!= null) {
 System.out.println("我是服务端,客户端说:" + temp); }
 System.out.println("客户端数据接收完毕--"); socket.shutdownInput(); System.out.println("开始服务端向客户端发送数据--"); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("这里是服务端发送的信息,我很好!n"); pw.flush(); socket.shutdownOutput(); System.out.println("结束服务端向客户端发送数据--"); os.close(); pw.close(); br.close(); isr.close(); is.close(); serviceSocket.close(); } catch (IOException e) {
//TODO Auto-generated catch block
 System.out.println(e.getMessage()); e.printStackTrace(); } finally {
 }
 }
}

Socket client

package com.taowd.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;/**
 * 功能:Socket通讯客户端
 * @author Taowd
 *
 */publicclassSocketClient {publicstaticvoidmain(String[] args) {
 try {
 //1、创建Socket实例,向服务端发送信息 Socket socket = new Socket("127.0.0.1", 8888);
 OutputStream os = socket.getOutputStream();
 PrintWriter pw = new PrintWriter(os);
 pw.write("这里是客户端,你好啊!");
 pw.flush();
 socket.shutdownOutput();
 //获取一个输入流,接收客户端发送的数据 InputStream is = socket.getInputStream();
 InputStreamReader isr = new InputStreamReader(is);
 BufferedReader br = new BufferedReader(isr);
 String temp = "";
 while ((temp = br.readLine())!= null) {
 System.out.println("这里是客户端,接收服务端信息为:" + temp);
 }
 socket.shutdownInput();
 br.close();
 isr.close();
 is.close();
 os.close();
 pw.close();
 socket.close();
 } catch (UnknownHostException e) {
 //TODO Auto-generated catch block e.printStackTrace();
 } catch (IOException e) {
 //TODO Auto-generated catch block e.printStackTrace();
 }
 }
}

Run results

这里写图片描述
这里写图片描述

project source code ( github )




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs