TCP Socket通訊
阿新 • • 發佈:2018-12-12
package jave; import java.io.*; import java.net.*; /*先啟動Server*/ public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(6666);//監聽在6666埠上 while(true) { //可以連線多個 Socket s = ss.accept();//接收Client端的連線 //接受Client端發來的東西 DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println(dis.readUTF()); dis.close(); s.close(); } } }
注意:Server只需啟動一次,切勿重複啟動,否則會出錯
package jave; import java.io.*; import java.net.*; import org.omg.CORBA.portable.OutputStream; public class TCPClient { public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException { Socket s = new Socket("127.0.0.1", 6666);//申請連結 //通過管道往Server裡寫東西 java.io.OutputStream os = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); // Thread.sleep(3000);//延遲3s讓Server讀取 dos.writeUTF("Hello Server!"); dos.flush(); dos.close(); s.close(); } }