Socket编程(网络编程)

网络通信的第一要素:IP地址 通过IP地址唯一的定位到互联网的主机

通过  IP+port(端口号)  来确定互联网的主机上的某个软件

InetAddress:位于java.net包下

getHostName():获取IP地址对应的域名

getHostAddress():获取IP地址

public class TestInetAddress{

  public static void main(String[] args){

    InetAddress inet = InetAddress.getByName("www.baidu.com");

    System.out.println(inet);

    System.out.println(inet.getHostName());

    System.out.println(inet.getHostAddress());

    // 获取本机的IP

    InetAddress inet1 = InetAddress.getLocalHost();

  }

}

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

// 客户端向服务器发送信息,服务器端接受信息并打印到控制台上,同时发送“已发送信息”给客户端
public class TestTCP2 {
// 客户端
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
// 建立通信
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9897);
// 向服务端发送信息
os = socket.getOutputStream();
os.write("哈哈,没我手速快吧".getBytes());
// 显示的告诉服务端发送完毕 shutdownOutput()
socket.shutdownOutput();
// 从服务端接受响应的信息
is = socket.getInputStream();
byte[] b = new byte[1024];
int len;
while ((len=is.read(b))!=-1) {
String str = new String(b, 0, len);
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

// 服务端
@Test
public void server(){
ServerSocket ss =null;
Socket s = null;
InputStream is =null;
OutputStream os = null;
try {
ss = new ServerSocket(9897);
s = ss.accept();
//读取客户端发送的数据
is = s.getInputStream();
byte[] b = new byte[1024];
int len;
while ((len=is.read(b))!=-1) {
String str = new String(b, 0, len);
System.out.println(str);
}
// 响应给客户端的数据
os = s.getOutputStream();
os.write("太突然了我考虑一下".getBytes());


} catch (Exception e) {
e.printStackTrace();
}finally {
try {
os.close();
is.close();
s.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


}

猜你喜欢

转载自www.cnblogs.com/qust-lgh/p/10408908.html