网络通信编程1-基本连接

服务器端:

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

public class Server {
	public static void main(String[] args) {
		ServerSocket ss = null;
		Socket serverSocket=null;
		try {
			 ss = new ServerSocket(9999);
			 /*
			  * 死循环,服务是不停止的。
			  */
			 while(true){
			 try {
					serverSocket = ss.accept();//等待客户端发来的数据
					System.out.println("connect is success!!!");
					System.out.println("look:" + ss.getLocalPort() + "ip:"
							+ ss.getInetAddress());
					PrintWriter out = new PrintWriter(
							serverSocket.getOutputStream(), true);
					out.println("hello.client");//发送到客户端
					/*
					 * 接收客户端的数据,
					 * serverSocket.getInputStream()接收字节流
					 * InputStreamReader(serverSocket.getInputStream())转换成字符流
					 * BufferedReader(new InputStreamReader(serverSocket.getInputStream()))放到缓冲中。
					 */
					BufferedReader br = new BufferedReader(new InputStreamReader(
							serverSocket.getInputStream()));
					String clientWold = br.readLine();
					System.out.println(clientWold);
				} catch (Exception e) {
						// TODO: handle exception
					}
			 }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ss!=null){
				try {
					ss.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}

 客户端:

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

public class Client {
	public static void main(String[] args) {
		Socket s2 = null;
		try {
		  s2 = new Socket("127.0.0.1",9999);
		  PrintWriter out = new PrintWriter(s2.getOutputStream(), true);
		  out.println("hello.world");//向服务器输出数据。
		  /*
		   * 接收服务器的数据。
		   */
		  BufferedReader br = new BufferedReader(new InputStreamReader(s2.getInputStream()));
		  String serverWord =  br.readLine();
		  System.out.println(serverWord);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(s2!=null){
				try {
					s2.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

你可能感兴趣的:(网络通信)