网络通信编程V2
远程建立通信连接:
以本地电脑演示
接收端
public class Server {
public void listneConnect(){
try {
ServerSocket sc =new ServerSocket(58888);
//使用while循环不断接收
while(true){
System.out.println("Listening.....");
Socket accept = sc.accept();
System.out.println("Connect :"+accept.getInetAddress());、
//建立接收
InputStream in = accept.getInputStream();
//接收发送字节数量
int msglength=in.read();
//接收发送过来的字节
byte[] bytes = new byte[msglength];
for (int i = 0; i < msglength; i++) {
bytes[i]= (byte) in.read();
}
//将收到的字节解析为字符串
System.out.println("get:"+new String(bytes));
accept.close();
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new Server().listneConnect();
}
}
发送端
public class Client {
public static void main(String[] args) {
try {
//确定目标ip地址和端口
Socket sc =new Socket("127.0.0.1",58888);
OutputStream os = sc.getOutputStream();
String msg="我是某某某";
//将字符串转为字节存入字节数组
byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
int msglength= bytes.length;
//写入长度信息
os.write(msglength);
//发送字节信息
for (int i = 0; i < msglength; i++) {
os.write(bytes[i]);
}
os.flush();
os.close();
sc.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
1.通信建立链接 只需要你把 IP+port写对
2.如果需要传输数据,一定要提前约定好消息体的协议,如发送文字 数字 等
3.发送一句话则是发送这句话占用多少字节和具体的字节内容并转化为正确的内容