Java 中与网络有关的包都存在于java.net包中。目前文章只用于记录demo。有些地方还不是很明白
客户端
package com.java;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args){
try{
Socket client = new Socket("127.0.0.1",8080);
OutputStream os= client.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("这是客户端发送的消息");
dos.close();
client.close();
}
catch(UnknownHostException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
服务端
package com.java;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
public static void main(String[] args){
try{
ServerSocket ssk = new ServerSocket(8080);
// 这是服务端不同的地方,需要先接收Socket
Socket sk = ssk.accept();
InputStream is = sk.getInputStream();
// 将字节流数据转化为数据流形式更加的方便
DataInputStream dis = new DataInputStream(is);
System.out.println("接收内容为:"+dis.readUTF());
}
catch(UnknownHostException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}