socket连接
最近找了找方向,随便翻了翻书,先写一些和主线无关的吧,socket连接的使用。
首先,如何连接远端的网络服务器。
先从最基本的说起:
Socket s = new Socket(...);as.setSoTimaOut(1000);try{ InputStream in = s.getInputStream();} catch(InterruptedIOException exception) { react to timeout}
Socket s = new Socket();s.connect(new InetSocketAddress(host, port), timeout);
InetAddress address = InetAddress.getByName("www.baidu.com");byte[] addressBytes = address.getAddress();//如果很多ip来实现负载均衡,则会有很多主机地址byte[] address = InetAddress.getAllByNames(hst);
ServerSocket s = new ServerSocket(8199);//下面的命令一下,你的程序就被hold住了哦Socket incoming = s.accept();//直到程序有了输入try{ InputStream inStream = incoming.getInputStream(); OutputStream outStream = incoming.getOutputStream(); Scanner in = new Scanner(inStream); PrintWriter out = new PrintWriter(outStream, true); out.print;n("Hello! Enter BYE to exit."); boolean done = false; while(!done && in.hasNextLine()){ String line = in.nextLine(); out.println("Echo" + line); if (line.trim().equals("BYTE")) done = true; }} finally { incoming.close();}catch(IOException e) { xxxx}}
while(true){ Socket incoming = s.accept(); Runnable r = new ThreadedEchoHandler(incoming); Thread t = new Thread(r); t.start(); i++;}
SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));Scanner in = new Scanner(channel);//Channels的静态方法OutputStream outputStream = Channels.newOutputStream(channel);