java从0开始学习第十四课-Socket真好玩!!!

    我们已经写过一个非常牛逼的爬虫了,我们还差Sockect,ServerSocket,今天就来一个非常吊的通信程序,做完这个程序之后,我们就能大声的对世界宣布:老子很牛!!!

   废话少说,这个程序大家一定会喜欢的,因为很好玩!先来一段服务器代码。大家复制粘贴到一个txt文件中,然后保存为:TestServer.java 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {
  public static void main(String[] args) {
	try{
		ServerSocket server=new ServerSocket(5678);
		Socket socket=server.accept();  
		InetAddress ipClient=socket.getInetAddress();
		String ipCliset=ipClient.getHostAddress();
		System.out.println(ipCliset+" 连上了我");
		InputStream in=socket.getInputStream();
		InputStreamReader iReader=new InputStreamReader(in);
		BufferedReader readerIn=new BufferedReader(iReader);
		BufferedReader readerOut=new BufferedReader(new InputStreamReader(System.in)) ;
		String s;
		
		PrintWriter pWriter=new PrintWriter(socket.getOutputStream());
		while (!(s=readerIn.readLine()).equals("不玩了")){
			System.out.println("客户端说:"+s);
			pWriter.println(readerOut.readLine()); //给客户端发送消息
			pWriter.flush();                       //刷新一下
		}
		
		System.out.println(ipCliset+" 断开连接了");
		in.close();//把资源都关闭了
		pWriter.close();
		socket.close();
		server.close();
		
	}catch (Exception e) {
		System.out.println("error "+e);
	}
}
}

 再来一个客户端,大家也把他复制粘贴了,然后保存为TestClient.java 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.sun.imageio.plugins.common.InputStreamAdapter;


public class TestClient {

	public static void main(String[] args) {
		try {
			Socket socket=new Socket("127.0.0.1",5678);
			PrintWriter out=new PrintWriter(socket.getOutputStream());
			BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//获取流读入器并且转换成缓存读入器
			BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
			String s;
			do {
				s=sin.readLine();//一行一行得读
				out.println(s);
				out.flush();
				if(!s.equals("不玩了")){
					System.out.println("服务器对我说:"+br.readLine());
				}else{
					System.out.println(" 睡觉去了···");
				}
			} while (!s.equals("不玩了"));
			sin.close();
			br.close();
			out.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

好了,跑这个程序比较特别,大家需要打开2个dos的窗口,先启动咱们的服务器,再启动客户端,然后就可以为所欲为啦。


java从0开始学习第十四课-Socket真好玩!!!_第1张图片
 

你可能感兴趣的:(java,java网络编程,socket例子,socket怎么用,socket入门例子)