📄 sockettest1.java
字号:
//This program opens a socket connection to an HTTP server, requests a resource// and receives the response. Copyright 2001 by Ted Kosan, Version 1.0.1package webtest;import java.net.*;import java.io.*;import javax.swing.JOptionPane;import javax.swing.JTextArea;import javax.swing.JScrollPane;public class SocketTest1{ private BufferedReader in; private PrintWriter out; private String inputLine; private Socket socket; //No parameter constructor. public SocketTest1() { //Call parent's constructor so that it can construct the part of the object //that it is responsible for. super(); } public void doSocketTest() { //This StringBuffer will hold the html response received from a web server. StringBuffer htmlCode = new StringBuffer(); try { //Create an InetAddress object that will hold the IP address of the server //we want to talk to. InetAddress iAddress = InetAddress.getByName("www.ibutton.com"); //Open a socket connection to the desired server using the specified port. socket = new Socket(iAddress, 80); //Open an output stream to the server so we can send information to it. out = new PrintWriter(socket.getOutputStream()); //Open an input stream to the server so we can receive information from it. in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Send an HTTP 'GET' request to the server. //out.print("GET /TINI/index.html HTTP/1.0\r\n\n"); out.print("GET / HTTP/1.0\r\n\n"); out.flush(); //Read the HTML response from the server a line at a time until the whole //response has been received. while((inputLine = in.readLine()) != null) { //Print each line as it is received to standard out. System.out.println(inputLine); //Copy each line into a StringBuffer so that we can display it later. htmlCode.append(inputLine); htmlCode.append("\n"); } //Close the socket connection socket.close(); //Instantiate a JTextArea and initialize it with the contents of //htmlCode, configure it, place it into a JScrollPane and //then show it in a JOptionPane dialog box. JTextArea ta = new JTextArea(htmlCode.toString()); ta.setColumns(80); ta.setRows(24); ta.setEditable(false); JScrollPane sp = new JScrollPane(ta); JOptionPane.showMessageDialog(null,sp); }//end try catch (UnknownHostException uhe) { uhe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); }//end catch //Shut down the JVM. System.exit(0); }//end method public static void main(String args[]) { SocketTest1 st = new SocketTest1(); st.doSocketTest(); }}//end class
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -