Java 简单Socket聊天系统模型(一)

 看过马士兵的教程中有关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();
		
		
	}

}


 

你可能感兴趣的:(Java 简单Socket聊天系统模型(一))