java基础回顾3 Socket 一次完整的服务器客户端交互

服务器端程序:

package yx.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	
	public static void main(String[] args) {
		ServerSocket ss=null;
		Socket s=null;
		String message="";
		try {
			ss = new ServerSocket(9999);
			s=ss.accept();
			String ip=s.getInetAddress().getHostAddress();
			InputStream in=s.getInputStream();
			byte[] buffer=new byte[1024];
			int len=0;
			while((len=in.read(buffer))!=-1){
				message+=new String(buffer,0,len);
			}
			System.out.println("服务器收到指令:"+message);
			
			OutputStream out=s.getOutputStream();
			out.write(message.getBytes());
			System.out.println("服务器发出指令:"+message);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(s!=null)
					s.close();
				if(ss!=null)
					ss.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}


客户端程序

package yx.socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {

	public static void main(String[] args) {
		Socket s=null;
		String message="哥哥,我来了!!!";
		try {
			s=new Socket("127.0.0.1", 9999);
			OutputStream out=s.getOutputStream();
			out.write(message.getBytes());
			
			System.out.println("客户端发送指令:"+message);
			InputStream in=s.getInputStream();
			byte[] buffer=new byte[1024];
			int len=0;
			while((len=in.read(buffer))!=-1){
				message+=new String(buffer,0,len);
			}
			System.out.println("客户端接受指令:"+message);
		}catch (Exception e) {
			e.printStackTrace();
		}
		

	}

}


你可能感兴趣的:(java,socket,网络编程)