(尚硅谷)21 网络web设计TCP协议

来源:互联网 发布:淘宝访客数计算公式 编辑:程序博客网 时间:2024/05/16 15:34
1.网络通信package com.atguigu.Net;import java.net.InetAddress;import java.net.UnknownHostException;/* * 1.网络编程中的两个主要问题 * >如何尊却定位网络上的一台或多台主机 *  >找到主机后如何可靠高效的进行数据传输 * 2.实现网络通信的两个要素:①IP地址 ,端口号 ②传输协议 * 3.如何创建一个InetAdress类对象 *  ①调用静态的getByName(String hostName)    *      ①域名 ②分配了一串数值:IP地址 *  ②getLocalHost () 获取本地的地址 *  4.getAdress的常用方法 : getHostName() ; getHostAdress() *  */public class InetAddressTest {public static void main(String[] args) {//实例化InetAddress对象,getByName();InetAddress inet = null;try {inet = InetAddress.getByName("www.atguigu.com");} catch (UnknownHostException e) {e.printStackTrace();}//两个方法的使用:getHostName() getHostAdress()System.out.println(inet);System.out.println(inet.getHostAddress());System.out.println(inet.getHostName());/*******************************/InetAddress inte1  = null;try {inte1 = InetAddress.getByName("42.121.6.2");} catch (UnknownHostException e1) {e1.printStackTrace();}System.out.println(inte1);System.out.println(inte1.getHostAddress());System.out.println(inte1.getHostName());/**********************************/InetAddress inet2 = null;try {inet2 = inet.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}System.out.println(inet2);System.out.println(inet2.getHostAddress());System.out.println(inet2.getHostName());}}/*************************************************/package com.atguigu.Net;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;public class TestNet {public static void main(String[] args) {Thread p1 = new Thread(new test1());Thread p2 = new Thread(new test2());Thread p3 = new Thread(new test2());p2.setName("kehu1");p3.setName("kehu2");p1.start();try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}p2.start();}}class test1 implements Runnable{public void run(){Server s = new Server(9012);s.read();System.out.println("3333");}}class test2 implements Runnable{public void run(){Client c =null;try {c =new Client(InetAddress.getByName("192.168.0.105") ,9012 );} catch (UnknownHostException e) {e.printStackTrace();}c.getConnect();c.talk();}}class Client{private InetAddress inet ; private int port ; private Socket socket ; public Client (InetAddress inet , int port){this.inet = inet ;this.port = port;System.out.println("客户端 目的地加载完成:"+inet+" "+port);}public void getConnect(){try {System.out.println("客户端启动..");socket = new Socket(inet, port);System.out.println("客户端启动完成!");} catch (IOException e) {e.printStackTrace();}System.out.println("连接成功"+inet.getHostName());}public void talk(){BufferedReader bin  = new BufferedReader(new InputStreamReader(System.in)); String str = "";BufferedWriter bw = null;try {bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); System.out.println("开始通话..");while((str = bin.readLine())!=null){System.out.println(Thread.currentThread().getName());if(str.equalsIgnoreCase("by")){socket.shutdownOutput();break;}bw.write(str);bw.newLine();bw.flush();}} catch (IOException e) {e.printStackTrace();}finally{if(bin!=null){try {bin.close();} catch (IOException e) {e.printStackTrace();}}if(bw!=null){try {bw.close();} catch (IOException e) {e.printStackTrace();}}if(socket!=null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}}class Server{ServerSocket serverSocket =null ;Socket socket = null;public Server (int doc){try {System.out.println("服务器加载..");serverSocket =new ServerSocket(9012);socket =serverSocket.accept();} catch (IOException e) {e.printStackTrace();}    System.out.println("waiting..");}public void read(){BufferedReader bin =null;try {bin = new BufferedReader(new InputStreamReader(socket.getInputStream()));} catch (IOException e1) {e1.printStackTrace();}String str = null;try {while((str = bin.readLine())!=null){System.out.println(str+"-->"+socket.getInetAddress().getHostName());}} catch (IOException e) {e.printStackTrace();}finally{if(bin!=null){try {bin.close();} catch (IOException e) {e.printStackTrace();}}if(socket!=null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}if(serverSocket!=null){try {serverSocket.close();} catch (IOException e) {e.printStackTrace();}}}}}/******************************************************************/package com.atguigu.Net;import java.net.Socket;public interface Writer {Socket getSocket();}package com.atguigu.Net;import java.net.Socket;public interface Lisener {Socket getSocket();}package com.atguigu.Net;import java.io.IOException;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;public class Clinet2 implements Lisener , Writer{private Socket socket = null;private InetAddress inet = null;private int code ;public Clinet2(InetAddress inet , int codde){this.inet = inet;this.code = codde;try {socket = new Socket(inet , code);} catch (IOException e) {e.printStackTrace();}System.out.println("建立客户端...");}public Socket getSocket() {return socket;}public void setSocket(Socket socket) {this.socket = socket;}public InetAddress getInet() {return inet;}public void setInet(InetAddress inet) {this.inet = inet;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}}package com.atguigu.Net;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class Server2 implements Lisener , Writer{ServerSocket serverSocket2 =null ;int codde ; Socket socket ;public Server2( int codde){this.codde = codde ;try {serverSocket2 = new ServerSocket( codde );} catch (IOException e) {e.printStackTrace();}System.out.println("建立服务器..");try {socket = serverSocket2.accept();} catch (IOException e) {e.printStackTrace();}System.out.println("建立服务器完成..");}public ServerSocket getServerSocket2() {return serverSocket2;}public void setServerSocket2(ServerSocket serverSocket2) {this.serverSocket2 = serverSocket2;}public int getCodde() {return codde;}public void setCodde(int codde) {this.codde = codde;}@Overridepublic Socket getSocket() {return socket;}}package com.atguigu.Net;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.Socket;public class ClentReadThread implements Runnable{private Lisener client =null;private InputStream in =null ;private BufferedReader bn = null;private Socket socket;public ClentReadThread (Lisener client){this.client = client;socket = client.getSocket();System.out.println("listener waiting..");}public void run(){try {in =socket.getInputStream();} catch (IOException e) {e.printStackTrace();}   listener();}public synchronized void listener(){try {in =socket.getInputStream();} catch (IOException e) {e.printStackTrace();}bn = new BufferedReader(new InputStreamReader(in));String str = null;System.out.println(Thread.currentThread().getName()+" listen..");try {while(true){str = bn.readLine();if(str.equalsIgnoreCase("by")){socket.shutdownInput();break;}System.out.println(Thread.currentThread().getName()+":"+str);}} catch (IOException e) {}}}package com.atguigu.Net;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.Socket;public class ClentWriterThread implements Runnable{private Writer client =null;private OutputStream out =null ;private BufferedWriter bn = null;private Socket socket;public ClentWriterThread (Writer client){this.client = client;socket = client.getSocket();System.out.println("Socket联接");}public void run(){System.out.println("开..");try {out =socket.getOutputStream();} catch (IOException e) {e.printStackTrace();} writer();}public synchronized void writer(){System.out.println("开..");try {out =socket.getOutputStream();} catch (IOException e) {e.printStackTrace();}BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));bn = new BufferedWriter(new OutputStreamWriter(out));String str = "hehe!!";try {while((str = bin.readLine())!=null){if(str.equalsIgnoreCase("by")){socket.shutdownOutput();break;}try {bn.write(str);bn.newLine();bn.flush();} catch (IOException e) {e.printStackTrace();}}} catch (IOException e) {e.printStackTrace();}}}package com.atguigu.Net;import java.net.InetAddress;import java.net.UnknownHostException;import org.junit.Test;//2.客户端给服务端发送信息,服务端收到信息打印到控制台,public class TestNet2 {Server2 server ;@Testpublic void Servered() { server = new Server2(9090);new ClentReadThread(server).listener();//Thread serverlisenner = new Thread(new ClentReadThread(server));//serverlisenner.setName("serverlisenner");//serverlisenner.start();//System.out.println("serverlisenner..begin");}@Testpublic void Clindered(){Clinet2 clinder = null ;try {clinder = new Clinet2(InetAddress.getLocalHost(),9090);} catch (UnknownHostException e) {e.printStackTrace();}new ClentWriterThread(clinder).writer();//Thread ClinderWriter = new Thread(new ClentWriterThread(clinder));//ClinderWriter.setName("ClinderWriter");//ClinderWriter.start();//System.out.println("ClinderWriter..begin");}}package dom2;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;public class MyClient implements Runnable {InetAddress friendsInet = null;InetAddress ServerInet = null;int ServerCode  = 0 ;int MyCode = 0;String friendaddress ;public MyClient(InetAddress ServerInet ,InetAddress friendsInet , int ServerCode , int MyCode ){this.ServerInet = ServerInet ;this.friendsInet = friendsInet;this.ServerCode = ServerCode;this. MyCode =  MyCode;this.friendaddress = friendsInet.getHostAddress();System.out.println("My客户端:"+ friendsInet +" "+ MyCode);}public void run(){Socket socket =null;try{System.out.println("链接服务器..");socket = new Socket( this.ServerInet , this.ServerCode);OutputStream outputstream = socket.getOutputStream();System.out.println("搭建信息船..");InputStream inputStream = System.in;System.out.println("开启输入口..");outputstream.write((friendaddress+"|"+MyCode+"|"+"ok").getBytes());outputstream.flush();byte [] b = new byte [100];int len = 0;while((len = inputStream.read(b))!=-1){outputstream.write((friendaddress+"|"+MyCode+"|"+new String(b , 0 , len)).getBytes());outputstream.flush();}}catch(IOException e){e.printStackTrace();}finally{if(socket !=null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}}package dom2;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 MyServer implements Runnable {int ServerCode  = 0 ;public MyServer(int ServerCode ){this.ServerCode = ServerCode;System.out.println("my服务器:"+ServerCode);}public void run(){Socket socket = null;InputStream in = null;try {System.out.println("子服务对接运端口..");ServerSocket serversocket = new ServerSocket(this.ServerCode);socket = serversocket.accept();System.out.println("对接成功..");in = socket.getInputStream();System.out.println("等待录入..");byte [] b = new byte[100];int len =0;while((len = in.read(b))!=-1){System.out.println(new String (b ,0 ,len ));}} catch (IOException e) {e.printStackTrace();}finally{if(in != null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(socket!=null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}}package dom2;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;public class ServerDao implements Runnable {int ServerCode = 0;public ServerDao(int ServerCode) {this.ServerCode = ServerCode;}public void run() {InputStream in = null;try {System.out.println("云平台建立..");ServerSocket serso = null;try {serso = new ServerSocket(ServerCode);} catch (IOException e) {e.printStackTrace();}System.out.println("等待数据..");Socket socket = null;try {socket = serso.accept();} catch (IOException e) {e.printStackTrace();}try {in = socket.getInputStream();} catch (IOException e) {e.printStackTrace();} String [] ms = new String[3];byte [] b = new byte [100];int len = 0;try {while((len = in.read(b))!=-1){System.out.println(Thread.currentThread()+ "getMessage:" + new String (b ,0 , len));ms = Arrs.ArrsFor(new String(b , 0 ,len));System.out.println("寻找对象");for(int i= 0 ;i<2 ;i++ ){System.out.println("--->"+ms[i]);}Socket socket2 = new Socket(InetAddress.getByName(ms[0]),Integer.parseInt(ms[1]));OutputStream out = socket2 .getOutputStream();out.write(ms[2].getBytes());out.flush();socket2.shutdownOutput();out.close();System.out.println("写出..");if(new String(b , 0 ,len).equalsIgnoreCase("by")){socket.shutdownOutput();break;}}} catch (IOException e) {e.printStackTrace();}} catch (RuntimeException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}}}class Arrs {public static String[] ArrsFor(String str) throws RuntimeException {String[] s = new String[3];int begin = 0;int idx = 0;if (str == null) {throw new RuntimeException("null");}l:for (int i = 0; i < 2; i++) {for (int j = begin; j < str.length(); j++) {if (str.charAt(j) == '|') {idx = j;s[i] = str.substring(begin, idx);//System.out.println(s[i]);begin = idx + 1;continue l;}}}s[2] = str.substring(begin, str.length());//System.out.println(s[2]);return s;}}package dom2;public class Test {public static void main(String[] args) {ServerDao dao = new ServerDao(9011);new Thread(dao).start();}}package dom2;import java.net.InetAddress;import java.net.UnknownHostException;public class Test1 {public static void main(String[] args) {try {MyServer server = new MyServer(9090);MyClient clinet = null;try {clinet = new MyClient(InetAddress.getByName("127.0.0.1"),InetAddress.getByName("127.0.0.1"), 9091, 9090);} catch (UnknownHostException e) {e.printStackTrace();}new Thread(server).start();Thread.sleep(2000);new Thread(clinet).start();}catch (InterruptedException e) {e.printStackTrace();}}}package dom2;import java.net.InetAddress;import java.net.UnknownHostException;public class Test2 {public static void main(String[] args) {try {MyServer server = new MyServer(9091);MyClient clinet = null;try {clinet = new MyClient(InetAddress.getByName("127.0.0.1"),InetAddress.getByName("127.0.0.1"), 9090, 9091);} catch (UnknownHostException e) {e.printStackTrace();}new Thread(server).start();Thread.sleep(2000);new Thread(clinet).start();}catch (InterruptedException e) {e.printStackTrace();}}}package dom3;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;public class ClientThread extends Thread {public void run(){OutputStream os=null;InputStream is=null;try {Socket s=new Socket(InetAddress.getByName("127.0.0.1"),9091);os=s.getOutputStream();is= System.in;byte [] b= new byte[10];int len;while((len=is.read(b))!=-1){os.write(b,0,len);}is.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}package dom3;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class ServerThread extends Thread{public void run(){try {ServerSocket ss=new ServerSocket(9090);Socket s=ss.accept();InputStream is=s.getInputStream();byte[]b=new byte[10];int len;while((len=is.read(b))!=-1){System.out.println(new String(b,0,len));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}package dom3;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import org.junit.Test;public class TestClintServer {public static void main(String[] args) {ClientThread ct =new ClientThread();ServerThread st = new ServerThread();st.start();ct.start();}/*@Test  public void test1(){//ServerThread st = new ServerThread();//st.start();try {ServerSocket ss=new ServerSocket(9385);Socket s=ss.accept();InputStream is=s.getInputStream();byte[]b=new byte[10];int len;while((len=is.read(b))!=-1){System.out.println(new String(b,0,len));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Testpublic void test2(){//ClientThread ct =new ClientThread();//ct.start();OutputStream os=null;InputStream is=null;try {Socket s=new Socket(InetAddress.getByName("192.168.10.34"),9385);os=s.getOutputStream();is= System.in;byte [] b= new byte[10];int len;while((len=is.read(b))!=-1){os.write(b,0,len);}is.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}*/}package Net;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import org.junit.Test;public class Sebd {@Testpublic void Test(){BufferedOutputStream out = null;BufferedReader readd = null;try {Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);out = new BufferedOutputStream(socket.getOutputStream());readd = new BufferedReader(new InputStreamReader(System.in));int len = 0;String str = null;while((str = readd.readLine())!=null){out.write(str.getBytes());out.flush();if(str.equals("by")){socket.shutdownOutput();break;}}readd = new BufferedReader(new InputStreamReader(socket.getInputStream()));String str1 ;while((str1 = readd.readLine())!=null){System.out.println(str1);}readd.close();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(readd!=null){try {readd.close();} catch (IOException e) {e.printStackTrace();}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void Test1(){BufferedInputStream in = null;BufferedWriter write = null;ServerSocket serverSocket = null;Socket socket = null;try {serverSocket = new ServerSocket (9090) ;System.out.println("Server..");socket = serverSocket.accept();in = new BufferedInputStream(socket.getInputStream());write = new BufferedWriter(new OutputStreamWriter(System.out));byte b [] = new byte[1024];int len ; while((len = in.read(b))!=-1){write.write(new String( b,0 ,len));write.newLine();write.flush();}try {BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());out.write("我收到..".getBytes());out.flush();out.close();} catch (IOException e) {e.printStackTrace();}} catch (IOException e) {e.printStackTrace();}finally{if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(write!=null){try {write.close();} catch (IOException e) {e.printStackTrace();}}}}}

0 0