您的位置:首页 > 理论基础 > 计算机网络

黑马程序员------网络编程概及其练习

2015-11-01 19:51 796 查看
------- android培训java培训、期待与您交流! ----------

计算机网络:

      是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。

网络编程:

 就是用来实现网络互连的不同计算机上运行的程序间可以进行数据交换。

下面为基本运行方式:

1,获取IP地址及其主机名称

  代码如下:

/*
网络编程:
IP地址

*/

import java.net.*;

class IPDemo
{
public static void main(String[] args) 	  throws Exception
{
InetAddress i = InetAddress.getLocalHost();
//获取IP地址
//System.out.println(i.toString());		// 获取主机名与IP
//System.out.println(i.getHostAddress());
//System.out.println(i.getHostName());
//获取主机名

InetAddress ia = InetAddress.getByName("115.239.211.112");

System.out.println(ia.getHostAddress());
System.out.println(ia.getHostName());
}
}


2,UDP协议 运行方式:

    缺点:(在我看来)要开两个窗口!!太不方便了,当然我们可以使用多线程解决。

优缺点:将数据及源和目的封装成数据中,不需要建立连接;

               每个数据报的大小在限制在64k内;

               因无连接,是不可靠协议;

              不需要建立连接,速度快;

/*
练习,有意思
类似聊天软件!!!!

第一次 一个文本里 写两个主函数!!
*/

import java.io.*;
import java.net.*;

class UdpSend2
{
public static void main(String[] args) 	 throws Exception
{
DatagramSocket ds = new DatagramSocket();

BufferedReader bufr = new BufferedReader(
new InputStreamReader(System.in));

String line = null;

while ((line = bufr.readLine())!=null)
{
if ("over".equals(line))
{
break;
}

byte [] buf = line.getBytes();

DatagramPacket dp = new DatagramPacket(
buf,buf.length,InetAddress.getByName("192.168.0.105"),2000);

ds.send(dp);
}

ds.close();

}
}

class UdpRece2

{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(2000);
//1, 建立端点

while(true)
{

// 2,定义数据包,用于存储数据
byte [] buf = new byte [1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);

ds.receive(dp);  // 阻塞式方法。
// 通过服务的receive方法将数据存入数据包中

String ip = dp.getAddress().getHostAddress();
String	data = new String(dp.getData(),0,dp.getLength());

System.out.println(ip+"::"+data);
}
}		   //关闭资源  ds.close();

}


3,TCP特点:

     建立连接,形成传输数据的通道;

    在连接中进行大数据量传输;

    通过三次握手完成连接,是可靠协议;

    必须建立连接,效率稍低;

/*

客户端:
1,建立socket服务,指定连接主机和端口。
2,获取socket流中的输出流,将数据写入该流中,通过网络发送给服务端
3,获取socket流中的输入流,将服务端反馈的数据获取到,并打印。
4,关闭客户端资源。

*/

class TcpClient2
{
public static void main(String[] args)
{
Socket s = new Socket("192.168.0.126",100003);

OutputStream out = s.getOutputSream();

out.write("你好".getBytes());

InputStream in = s.getInputStream();

byte [] buf = new byte[1024];

int len = in.read(buf);

System.out.println(new String(buf,0,len)) ;

s.close();
}
}

class TcpServer2
{
public static void main(String [] args)
{

ServerSocket ss = new ServerSocket(100003);

Socket s = ss.accept();

String ip = s.getIntAddress().getHostAddress();

System.out.println(ip+"...connected");

InputStream in = s.getInputStream();

byte[] buf = new byte[1024];

int len = in.read(buf);
System.out.println(new String(buf,0,len));

OutputStream out = s.getOutputStream();

out.write("哥们收到了".getBytes());

}
}

下面是今天的一个练习:

/*

有五个学生,每个学生3门课的成绩,
从键盘输入数据(姓名,三门课成绩),
并把学生的信息和计算出的总分高低顺序放在“stud。txt”

1,描述学生对象,
2,定义一个课操作学生对象的工具类。

思想:
1,通过键盘录入一组数据,并将该行信息取出封装成学生对象
2,因为学生有很多,那么就需要储存,使用到集合。因为要排序
TreeSet
3,将集合的信息写入到一个文件中。
*/

import java.io.*;
import java.util.*;

class Student		  //建立学生对象,并进行封装。
{
private String name;			 //进行私有化
private int cn,math,english;
private int sum;
void student(String name,int cn,int math,int english)
{
this.name=name;
this.cn=cn;				  // 赋值
this.math=math;
this.english=english;
sum=cn+math+english;		//不要忘记创建sum

}

public String getname()			 //调用参数
{
return name;

}
public int getsum()
{
return sum;
}

public int hashCode()				  // 哈希值一定要复写
{
return name.hashCode+sum*56;

}

public boolean equals(Object obj)
{
if (!(obj instanceof Student))
{
throw new ClassCastException("类型不匹配") ;
}

Student s = (Student) obj;

return this.name.equals(s.name) && this.sum==s.sum;
}

public String toString()
{
return "student["+name+"'"+cn+","+math+"'"+english+"]" ;
}

}

class CompareStudent			// 创建比较方法,及其写入
{
public static Set<Student> getStudents() throws IOException
{
BufferedReader bufr=new BufferedReader(
new InputStreamReader(System.in) );

Set<Student> ts=new TreeSet<Student>();
String len=null;
while ((len=bufr.readLine())!=null)
{
if ("over".equals(len))
{
break;
}
String [] info = len.split(",") ; //切割“,”,用于读取

Student stu = new Student(info[0],Integer.parseInt(info[1]),
Integer.parseInt(info[2]),
Integer.parseInt(info[3]))	;
ts.add(stu);

}

bufr.close();
return ts;
//bufw.close();
}

public static void write2File(Set<Student> ts)
{
BufferedWriter  bufw= new BufferedWriter(
new FileWriter("Student.txt"))	;

for (Student stu:ts )
{
bufw.write(stu.toString());
bufw.write(stu.getsum());
}

}

}

class  CopStudent					 //主函数 调用
{
public static void main(String[] args)
throws IOException
{
CompareStudent.	getStudents();
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: