范例1:定义服务器端——主要使用SeverSokcet
·构造方法:public ServerSoket(int port)throws IOException;
·接收客户端连接:public Socket accept()throws IOException;
·取得客户端输出功能,Socket 类定义方法:public OuputStream getOutputStream()throws IOException。
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo {
public static void main(String[] args) throws Exception {// 此处直接抛错
ServerSocket server = new ServerSocket(9999);
System.out.println("等待客户端连接....");
Socket client = server.accept();// 等待客户端链接
// OutputStream并不方便进行内容输出,所以转换为PrintStream
PrintStream out = new PrintStream(client.getOutputStream());
out.println("我是共产主义接班人");
out.close();
client.close();
server.close();
}
}
============分割线============
范例2:编写客户端——Sokcet
·构造方法:public Socket(String host,int port)throws UnknowHostException,IOException;
|-host表示主机的IP地址,如果是本机直接访问那么使用localhost代替IP;
·得到输入数据:public InputStream getInputStream()throws IOException。
import java.net.Socket;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) throws Exception {// 直接抛出异常
Socket client = new Socket("localhost", 9999);// 连接服务器端
// 取得客户端的输入数据对象,表示接收服务器端的输出信息
Scanner scan = new Scanner(client.getInputStream());
scan.useDelimiter("\n");
if (scan.hasNext()) {
System.out.println("【回应数据】:" + scan.next());
}
scan.close();
client.close();
}
}