Java 网络编程(基本实现)

范例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();
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值