学习目标:
socket编程(客户端和服务器端实现对话)
学习内容:
网络通信基本概念:
通信: 就是从一台机器上的一个软件,发送数据到另一台机器的一个软件上。
概念: 先发送数据的软件:称为客户端
被动接收数据的软件:称为服务端
数据从一台机器发到另一台机器,目标地址如何指定?通过对方的ip和端口
JAVA中写socket的基本代码:
服务端:
ServerSocket ss = new ServerSocket(10000);
Socket sc = ss.accept();
InputStream in = sc.getInputStream();
OutputStream out = sc.getOutputStream();
in.read() //接收:一次读一个字节
in.read(buf)// 接收:一次读buf长度个字节
out.write("aaa".getBytes) // 发送数据
客户端:
Socket sc = new Socket(“192.168.10.130”,10000)
// 然后收发数据即可
示例:
1、一次通信
//**服务器端**
public class ServerDemo {
public static void main(String[] args) throws Exception {
// 启动一个socket服务端(本质就是向操作系统注册一个端口号)
ServerSocket ss = new ServerSocket(10000);
System.out.println("服务端启动......,监听的端口为10000");
// (监听这个端口上的消息)
Socket sc = ss.accept(); // 等待并接收客户端的请求,建立socket连接; 这是一个阻塞方法
/**
* 从连接中接收数据
*/
// 从连接中接收数据,需要先获得一个输入流工具
InputStream in = sc.getInputStream();
// 从输入流中拿数据
/*int read = 0;
while((read = in.read())!=-1) {
System.out.println((char)read);
}*/
byte[] b = new byte[1024];
int num = in.read(b);
String string = new String(b,0,num);
System.out.println("收到客户端的消息:" + string);
/**
* 发送数据
*/
OutputStream out = sc.getOutputStream();
out.write("我是红红".getBytes());
//关流
out.close();
in.close();
sc.close();
}
}
//**客户端**
public class ClientDemo {
public static void main(String[] args) throws Exception {
// 向服务端发出建立连接的请求
Socket sc = new Socket("127.0.0.1", 10000);
/**
* 发送数据
*/
// 从连接中拿到一个发数据的工具
OutputStream out = sc.getOutputStream();
// 利用out流发数据
out.write("who are you?".getBytes());
/**
* 接收数据
*/
InputStream in = sc.getInputStream();
byte[] b = new byte[10];
int num = in.read(b);
System.out.println(new String(b,0,num));
//关流
in.close();
out.close();
sc.close();
}
}
2、多次通信,实现对话
//**服务器端**
public class ServerDemo3 {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8080);
int i = 1;
while(true) {
Socket sc = ss.accept();
System.out.println("获得第"+i+"次连接了.....");
InputStream in = sc.getInputStream();
OutputStream out = sc.getOutputStream();
// 收客户端的第一个问题
byte[] b = new byte[1024];
int num = in.read(b);
System.out.println("收到客户端的第1个问题: " + new String(b,0,num));
// 回答第一个问题
out.write("我是小狗".getBytes());
// 接收第二个问题
num = in.read(b);
System.out.println("收到客户端的第2个问题: " + new String(b,0,num));
// 回答第2个问题
out.write("小猫".getBytes());
in.close();
out.close();
sc.close();
i++;
}
}
}
//**客户端**
public class ClientDemo3 {
public static void main(String[] args) throws Exception {
Socket sc = new Socket("127.0.0.1",8080);
InputStream in = sc.getInputStream();
OutputStream out = sc.getOutputStream();
// 先发第一个问题
out.write("你是谁啊?".getBytes());
// 接收第一个问题的答案
byte[] b = new byte[1024];
int num = in.read(b);
System.out.println("第一个问题的答案是: " + new String(b,0,num));
Thread.sleep(10000); //模拟:有些客户端可能很墨迹
// 发第2个问题
out.write("你的理想女友是?".getBytes());
// 接收第2个问题的答案
num = in.read(b);
System.out.println("第2个问题的答案是: " + new String(b,0,num));
in.close();
out.close();
sc.close();
}
}