java socket编程 初级 服务器端和客户端 通信

package server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Server {

	public Server() {

	}

	public static void main(String[] args) {
		Server manager = new Server();
		manager.doListen();
	}

	public void doListen() {
		ServerSocket server;
		try {
			server = new ServerSocket(9991);
			System.out.println("server 启动!");
			
			Socket client = server.accept();
			new Thread(new SSocket(client)).start();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 服务器进程
	class SSocket implements Runnable {

		Socket client;

		public SSocket(Socket client) {
			this.client = client;
		}

		public void run() {
			DataOutputStream output = null;
			try {
				output = new DataOutputStream(client.getOutputStream());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			while (true) {
				try {
					output.writeBytes("hi !\r\n");
					String ly_time = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
					System.out.println(ly_time +"  发送: hi ! ");
				} catch (IOException e) {
					e.printStackTrace();
				} 
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

Client
package client;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Client {

	public static void main(String[] args) {
		Socket socket = null;
		try {
			
			socket = new Socket("127.0.0.1", 9991);
			socket.setSoTimeout(5000);
			System.out.println("Client 已连接");
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		DataInputStream in = null;
		while (true) {
			try {
				in = new DataInputStream(socket.getInputStream());
				String res = in.readLine();
				String ly_time = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
				System.out.println(ly_time+"  接受:"+res);
			} catch (SocketException e) {
				System.out.println("SocketException ::::"+e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
			}  			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}



posted on 2013-09-26 17:38  道法自然smile  阅读(182)  评论(0编辑  收藏  举报