Java如何實(shí)現(xiàn)簡(jiǎn)單后臺(tái)訪(fǎng)問(wèn)并獲取IP
后臺(tái)服務(wù)端
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(1122);//服務(wù)器端口號(hào) Socket ss = s.accept();// 獲取IP訪(fǎng)問(wèn)者IP地址 String cip = ss.getInetAddress().getHostAddress();// 接收信息獲取訪(fǎng)問(wèn)姓名身份同時(shí)向訪(fǎng)問(wèn)者問(wèn)好 String msg = String.format('%s:Hellosn', 'wo', cip); OutputStream os = ss.getOutputStream(); PrintWriter out = new PrintWriter(os); out.write(msg); out.flush(); System.out.println('有人連線(xiàn)了: ' + cip);// 讀取信息 InputStream is = ss.getInputStream(); System.out.println(new String(is.readAllBytes())); System.out.println(ss.isConnected()); os.close(); }}
客戶(hù)端
import java.io.*;import java.net.Socket;public class Client { public static void main(String[] args) throws IOException { Socket client = new Socket('192.168.1.16', 1122);//服務(wù)器端口號(hào)1122,IP也可以自定義訪(fǎng)問(wèn)也可以在IP那里輸入localhost訪(fǎng)問(wèn)本機(jī) if (client.isConnected()) {// 接收信息 InputStream is = client.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); System.out.println(br.readLine());//向服務(wù)器發(fā)送個(gè)人信息 String msg = '學(xué)生:xxxrn';//名字可以定義 OutputStream os = client.getOutputStream(); os.write(msg.getBytes()); os.flush(); System.out.println(client.isConnected()); System.out.println(client.isClosed()); is.close(); os.close(); } }}
后臺(tái)接收的信息

客戶(hù)端接收的信息

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP驗(yàn)證碼工具-Securimage2. Vue 實(shí)現(xiàn)對(duì)quill-editor組件中的工具欄添加title3. JavaScript實(shí)現(xiàn)簡(jiǎn)單的彈窗效果4. 我所理解的JavaScript中的this指向5. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)6. PHP利用curl發(fā)送HTTP請(qǐng)求的實(shí)例代碼7. Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求8. PHP單件模式和命令鏈模式的基礎(chǔ)知識(shí)9. 一文帶你徹底理解Java序列化和反序列化10. js實(shí)現(xiàn)碰撞檢測(cè)

網(wǎng)公網(wǎng)安備