socket编程

socket是网络编程的基础,虽然说现在的开发中很多都是有已经封装好的socket通信框架,但是学习socket还是很有必要的

socket客户端

public class MinaClient {

public static void main(String args[]){
   MinaClient minaClient=new MinaClient();
   minaClient.start();
}
public void start(){
	//第一步,创建socket对象
	 Socket socket=null;
	 //第二步,创建流
	 OutputStreamWriter outputStreamWriter=null;
	 BufferedWriter writer=null;
	 BufferedReader reader=null;
	try {
         socket=new Socket("127.0.0.1",9988);
		outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
		writer = new BufferedWriter(outputStreamWriter);
		reader = new BufferedReader(new InputStreamReader(System.in));
		String msg;
		//第三步,读写流
		while(!(msg=reader.readLine()).equals("\n")){
		    writer.write(msg+"\n");
		    writer.flush();//注意flush是清空缓存中的数据,如果没有调用这个方法就关闭writer会导致数据丢失
			System.out.println(msg);
		}
		
	} catch (UnknownHostException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	finally{
		try {
			//第四步,关闭socket和流
			socket.close();
			reader.close();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}
}
socket服务器端
public class MinaServer {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("main");
		MinaServer server=new MinaServer();
      server.startServer();
	}
	public void startServer(){
		//第一步,创建socketserver对象
		 ServerSocket serverSocket = null;
		 //第二步,创建流对象
		 BufferedReader reader = null;
		try {
		 serverSocket=new ServerSocket(9988);
		 //第三步,等待客户端接入
		 Socket socket=serverSocket.accept();
		 reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		 String lineString;
		 //第四步,读写
		 while((lineString=reader.readLine())!=null){
			 System.out.println("client"+socket.hashCode()+":"+lineString);
		 }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				//第五步,关闭socket和流
				serverSocket.close();
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值