昨天寫了段小程序,現貼出來看看。javascript
如下是socket的簡單介紹。獲取兩臺聯通的機器之間的IP和端口號等信息。html
import java.io.IOException; import java.net.Socket; public class SockerDemo { public static void main(String[] args) throws IOException { Socket socket = new Socket(); System.out.println(socket.getLocalAddress());//這些方法用於獲取本地和遠程的一些信息 System.out.println(socket.getLocalPort()); System.out.println(socket.getInetAddress()); // System.out.println(socket.getInputStream()); System.out.println(socket.isClosed()); System.out.println(socket.isBound()); System.out.println(socket.isConnected()); } }
在IDEA工程中,同一src包下。java
ServerSocket 這個類的主要功能是監聽本機的一個端口。當有事件發生的時候(或者說新的鏈接到達的時候),新建一個Socket對象,用於與所鏈接機器與本機的交互。小程序
import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketDemo { static ServerSocket serverSocket = null; public ServerSocketDemo() throws IOException { } public static void main(String[] args) throws IOException { serverSocket = new ServerSocket(8888); service(); } public static void service() { while (true) { Socket socket = null; try { socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[20480]; inputStream.read(bytes); System.out.println(new String(bytes)); //OutputStream這個類繼承自FileOutputStream OutputStream outputStream = socket.getOutputStream(); File file = new File("src/file.html"); FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(bytes); outputStream.write(bytes); socket.close(); outputStream.close(); System.out.println("新增鏈接:" + socket.getInetAddress() + ":" + socket.getPort()); } catch (Exception e) { e.printStackTrace(); } } } }
這是file.html文件。運行上述Java程序,當在瀏覽器中請求127.0.0.1:8888的時候,瀏覽器可跳轉到如下界面。瀏覽器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="src/encoder.js"></script> <title>Title</title> </head> <body> 我要請求一張圖片 <img src="src/timthumb.jpg"> </body> </html>
目前只能傳點文字。socket
<img src="src/timthumb.jpg">這一行未執行成功。今天想個辦法處理一下圖片的傳送和js文件的傳送。.net