第十八章 JAVA网络编程
- 网络分层模型
OSI七层:物理层-数据链路层-网络层-传输层-会话层-表示层-应用层;
TCP/IP四层:网络接口层-网络互联层-传输层-应用层; - 网络端口号数量:65536个;
示例:
客户端:
public static void main(String[] args) {
TODO Auto-generated method stubString message = JOptionPane.showInputDialog("你想对服务器说点啥?"); Socket socket = null; BufferedWriter bw = null; try { //产生Socket对象,产生时告知IP地址和端口号 socket = new Socket("127.0.0.1", 9527); //通过输出流操作,发送信息。
socket.getOutputStream().write(message.getBytes());
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(message);
bw.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//关闭socket
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}
服务端:public class MessageThread extends Thread {
private Socket socket;public MessageThread(Socket socket){
this.socket = socket;
}public void run(){
// 从Socket里面取消息
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//得到套接字的输入流与计算机输入流对接,再与阅读器对接;
String str = br.readLine();
System.out.println(“客户端说:” + str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
服务端线程:
public static void main(String[] args) {
// TODO Auto-generated method stubServerSocket server = null; try { // 产生一个ServerSocket对象 server = new ServerSocket(9527); while (true) { System.out.println("开始监听......"); // 开始监听,一旦得到消息就会返回给我们一个Socket对象 Socket socket = server.accept(); MessageThread th = new MessageThread(socket); th.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 用完以后要关闭 if (server != null) { try { server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
}
未完待续