java socket 客户端和服务器端互相通信(聊天)

客户端:

package com.lzx.socket;

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

public class SocketClient {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		final Socket socket = new Socket("127.0.0.1", 10000);
			
		//回复服务端
		new Thread(){
			public void run() {
				try {
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
					BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
					String readline = in.readLine();
					System.out.println(readline);
					while(true){
						out.println(readline);
						System.out.println(" client send: " + readline);
						readline = in.readLine();
						if(readline.equals("bye"))
							break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		
		new Thread(){
			public void run() {
				//获得客户端发来的数据
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while(true){
						System.out.println("Receive from server : " + reader.readLine());
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		
	}

}


服务端:

package com.lzx.socket;

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 SocketServer {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(10000);
		final Socket socket = server.accept();
		
		new Thread(){
			public void run() {
				//获得客户端发来的数据
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while(true){
						System.out.println("Receive from client : " + reader.readLine());
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		new Thread(){
			public void run() {
				try {
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
					BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
					String readline = in.readLine();
					System.out.println(readline);
					while(true){
						out.println(readline);
						System.out.println(" server send: " + readline);
						readline = in.readLine();
						if(readline.equals("bye"))
							break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

}


上一篇:Windows 7版本IE10浏览器11月中旬推出


下一篇:20160318了解oracle版本升级的一些参数变化