基於TCP協議的Socket通訊案例
阿新 • • 發佈:2018-12-07
客戶端程式碼
import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class Main { public static void main(String[] args) throws IOException { Socket s = new Socket(InetAddress.getByName("SKY-20180725WBH"), 10077); OutputStream os = s.getOutputStream(); String str = "hello tcp, i am coming."; os.write(str.getBytes()); os.close(); s.close(); } }
服務端程式碼
import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Receive { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10077); Socket cs = ss.accept(); System.out.println(cs); InputStream is = cs.getInputStream(); byte[] bys = new byte[1024]; int len; len = is.read(bys); InetAddress address = ss.getInetAddress(); System.out.println(new String(bys, 0, len)); System.out.println(cs.getPort()); System.out.println(cs.getInetAddress()); System.out.println(); System.out.println(cs.getPort()); cs.close(); // ss.close(); //服務端可以不關 } }