1、IP地址:
唯一标识internet上的计算机,起定位作用。
InetAddress类位于java.net包中
一个InetAddress对象就代表一个IP地址
创建InetAddress对象:通过调用getByName(“域名”)
getHostName()获取域名
getHostAddress()获取IP地址
getLocalHost()获取本机IP地址
例子:public static void main(String[] args) throws UnknownHostException {
InetAddress inet = InetAddress.getByName("www.baidu.com");
System.out.println(inet);
System.out.println(inet.getHostAddress());
System.out.println(inet.getHostName());
InetAddress b= InetAddress.getLocalHost();
System.out.println(b);
}
端口:标识正在计算机运行的进程
不同的进程有不同的端口号
端口与IP的联系:IP区分不同的电脑,端口区分不同的进程(应用程序)
TCP和UCP协议
Socket允许程序把网络连接当做一个流,数据在两个Socket之间传输。网络编程实际上是Socket编程
public class TCPtest {
public void client(){
Socket socket=null;
OutputStream out=null;
try {
socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);//服务器的ip地址,及端口号。
out=socket.getOutputStream();//发送数据.
out.write("我成功了".getBytes());
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
public void server(){
ServerSocket a=null;
Socket ss=null;
InputStream is=null;
try {
a = new ServerSocket(9090);
ss = a.accept();//调用该方法,返回Socket的对象
is = ss.getInputStream();//调用Socket的对象的getInputStream()获取一个从客户端发送过来的输入流
//对流的操作.
int len;
while((len=is.read(b))!=-1){
String str=new String(b,0,len);
System.out.println(str);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(ss!=null){
try {
ss.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(a!=null){
try {
a.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
Socket.shundownOutput()执行此方法,告诉服务端,客户端的东西发送完毕。
UDP网络通信
类DatagramSocket(UDP数据报通过这类发送和接受)和DatagramPacket(这类封装了UPD数据报,在数据报中包含了发送端和接收端的IP地址和端口,因此无须建立接收方和发送方)实现UDP协议网络程序
系统不保证UDP数据报一定能够安全送到目的地。也不能确定什么时可以抵达。
public class UDPTest {
@Test
public void send(){
DatagramSocket a=null;
try {
a = new DatagramSocket();
byte[] b="niaho".getBytes();
DatagramPacket dp=new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9090);
a.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(a!=null){
a.close();
}
}
}
@Test
public void receive(){
DatagramSocket ds=null;
try {
ds = new DatagramSocket(9090);
byte[] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b,0,b.length);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ds!=null)
ds.close();
}
}