收發數字
阿新 • • 發佈:2018-12-29
cat tooltip ane 打印 .html highlight adding htm 端口
1. 客戶端打開輸出流,並發送數字 110
2. 服務端打開輸入流,接受數字 110,並打印
一旦建立了連接,服務端和客戶端就可以通過Socket進行通信了
1. 客戶端打開輸出流,並發送數字 110
2. 服務端打開輸入流,接受數字 110,並打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package socket;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket; import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket( "127.0.0.1" , 8888 );
// 打開輸出流
OutputStream os = s.getOutputStream();
// 發送數字110到服務端
os.write( 110 ); os.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket( 8888 );
System.out.println( "監聽在端口號:8888" );
Socket s = ss.accept();
//打開輸入流
InputStream is = s.getInputStream();
//讀取客戶端發送的數據
int msg = is.read();
//打印出來
System.out.println(msg);
is.close();
s.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
收發數字