tcp

public class client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		/**
		 * 创建tcp客户端socket,使用socket对象初始化连接通道
		 * 如果连接建立成功,说明数据传输通道已建立,该通道就是socket流,是底层建立好的
		 * 可以通过getOutputStream,getInputStream获取字节流
		 * 使用输出流将数据写出
		 * 关闭资源
		 */
		//创建客户端socket
		Socket socket = new Socket("192.168.0.102", 10001);
		//获取socket输出流
		OutputStream out = socket.getOutputStream();
		out.write("tcp来了".getBytes());//阻塞
		
		InputStream is = socket.getInputStream();
		byte[] buf = new byte[1024]; 
		int len = is.read(buf);//阻塞
		String text = new String(buf,0,len);
		System.out.println(text);
		
		
		socket.close();
	}
}
public class server {
	public static void main(String[] args) throws IOException {
		/**
		 * 创建服务端socket,ServerSocket对象
		 * 服务端必须对外提供端口,否则客户端无法连接
		 * 获取连接过来的客户端对象
		 * 通过客户端对象获取socket流,读取客户端发来的数据
		 * 关闭资源 关客户端 关服务端
		 */
		
		ServerSocket ss = new ServerSocket(10001);
		Socket s = ss.accept(); //阻塞
		String ip = s.getInetAddress().getHostAddress();
		InputStream is =  s.getInputStream();
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		String text = new String(buf,0,len);
		System.out.println(ip + " server:"+text);
		
		OutputStream os = s.getOutputStream();
		os.write("收到".getBytes()); //阻塞
		
		s.close();
		ss.close();
		
	}
}

注意换行标记和自动刷新

public class TransClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		//创建客户端socket
		Socket socket = new Socket("192.168.0.102", 10004);
		//创建输出输入流
		BufferedReader isr = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(socket.getOutputStream(),true); //自动刷新 ,免得后面写flush
		BufferedReader bufin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		
		String line = null;
		//发送,接收
		while((line=isr.readLine())!=null) {
			if("exit".equals(line)) {
				break;
			}
			out.println(line); //必须ln有换行标记,否则服务算readline会阻塞
			
			String upperString = bufin.readLine();
			System.out.println("服务端发来: "+upperString);
		}
		
		socket.close();
		
	}
}
public class TransServer {
	public static void main(String[] args) throws IOException {
		
		ServerSocket ss = new ServerSocket(10004);
		Socket socket = ss.accept();
		String ip = socket.getInetAddress().getHostAddress();
		System.out.println(ip + "connect....");
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter pw = new PrintWriter(socket.getOutputStream(),true); //自动刷新 ,免得后面写flush
		
		String line = null;
		while((line=br.readLine())!=null) {
			System.out.println(ip+"客户端发来: "+line);
			String upperString = line.toUpperCase();
			pw.println(upperString); //必须ln有换行标记,否则客户端readline会阻塞
		}
		
		socket.close();
		ss.close();
		
		
	}
}

上传文件

public class UpFileClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		System.out.println("上传客户端。。。。。。");
		
		File file = new File("d:\\client.txt");
		System.out.println(file.exists());

		Socket s = new Socket("192.168.0.102",10005);

		BufferedReader bufr =
				new BufferedReader(new FileReader(file));

		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		
		
		String line = null;
		while((line=bufr.readLine())!=null){
			
			out.println(line);
		}
		
		//告诉服务端,客户端写完了。
		s.shutdownOutput();
//		out.println("!@#$%^&*(");
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		String str = bufIn.readLine();
		System.out.println(str);
		
		bufr.close();
		s.close();
	}
}

public class UpFileServer {
	public static void main(String[] args) throws IOException {
		
		System.out.println("上传服务端。。。。。。。。。");
		
		ServerSocket ss = new ServerSocket(10005);
		
		Socket s = ss.accept();
		
		System.out.println(s.getInetAddress().getHostAddress()+".....connected");
		
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		BufferedWriter bufw = new BufferedWriter(new FileWriter("d:\\server.txt"));
		
		String line = null;
		
		while((line=bufIn.readLine())!=null){
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
		}
		
		
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		out.println("上传成功");
		
		bufw.close();
		
		s.close();
		ss.close();
	}
}

上传图片

public class UpImageServer {
	public static void main(String[] args) throws IOException {
		
		ServerSocket ss = new ServerSocket(10006);
		
		Socket s = ss.accept();
		
		System.out.println(s.getInetAddress().getHostAddress()+".....connected");
		
		InputStream is = s.getInputStream();
		FileOutputStream fos = new FileOutputStream("d:\\2.psd");
		
		int len = 0;
		byte[] buf = new byte[1024];
		while((len=is.read(buf))!=-1) {
			fos.write(buf,0,len);
		}
		OutputStream out = s.getOutputStream();
		out.write("上传成功".getBytes());
		
		fos.close();
		s.close();
		ss.close();
		
	}
}

public class UpImageClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket s = new Socket("192.168.0.102",10006);
		
		FileInputStream fis = new FileInputStream("d:\\1.psd");

		OutputStream out = s.getOutputStream();
		
		
		byte[] buf = new byte[1024];
		int len=0;
		while((len=fis.read(buf))!=-1){
			
			out.write(buf,0,len);
		}
		s.shutdownOutput();
		
		InputStream in = s.getInputStream();
		byte[] bufin =new byte[1024];
		int lenin = in.read(bufin);
		String textString = new String(bufin,0,lenin);
		System.out.println(textString);
		
		fis.close();
		s.close();
	}
}

多线程

public class UpImageServer {
	public static void main(String[] args) throws IOException {
		
		ServerSocket ss = new ServerSocket(10006);
		while(true) {
			Socket s = ss.accept();
			new Thread(new ImageDeal(s)).start();
		}
		
	}
}

public class ImageDeal implements Runnable {

	private Socket s;
	
	public ImageDeal(Socket s) {
		this.s = s;
	}
	
	@Override
	public void run() {
		try {
			System.out.println(s.getInetAddress().getHostAddress()+".....connected");
			
			InputStream is = s.getInputStream();
			int name = (int)(1+Math.random()*(100000-1+1));
			FileOutputStream fos = new FileOutputStream("d:\\"+name+".psd");
			
			int len = 0;
			byte[] buf = new byte[1024];
			while((len=is.read(buf))!=-1) {
				fos.write(buf,0,len);
			}
			OutputStream out = s.getOutputStream();
			out.write("上传成功".getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}

}

自定义WEB服务器和浏览器(简易)

public class MyTomcat {
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(9998);
		Socket s = ss.accept();
		System.out.println(s.getInetAddress().getHostAddress());
		InputStream in = s.getInputStream();
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		String text = new String(buf,0,len);
		System.out.println(text);
		
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		out.println("HTTP/1.1 404");

		s.close();
		ss.close();
	}
}
public class MyBrower {
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("192.168.0.102",9998);
		
		PrintWriter req = new PrintWriter(socket.getOutputStream(),true);
		
		req.println("GET /?id=1 HTTP/1.1");
		req.println("Host: 192.168.0.102:9998");
		req.println("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0");
		req.println("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		req.println("Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3");
		req.println("Accept-Encoding: gzip, deflate");
		req.println("Connection: keep-alive");
		
		InputStream res = socket.getInputStream();
		byte[] buf = new byte[1024];
		int len = res.read(buf);
		String string = new String(buf,0,len);
		System.out.println(string);
		
		socket.close();
	}
}

url

public class URLDemo {
	public static void main(String[] args) throws IOException {
		String surl = "http://192.168.0.102:9999/index.html";
		URL url = new URL(surl);
		
		//InputStream req = url.openStream();
		
		URLConnection conn = url.openConnection();
		System.out.println(conn.getHeaderField("Date"));
		
		InputStream req = conn.getInputStream();
		byte[] buf = new byte[1024];
		int len=req.read(buf);
		String res = new String(buf,0,len);
		System.out.println(res);
		req.close();
	}
}

书籍推荐