当前位置: 首页 > 工具软件 > Internal Chat > 使用案例 >

chat客户端

舒阳州
2023-12-01
import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class newclient {
	private Socket socket;
	public newclient()   {
		try {
			socket=new Socket("localhost", 1234);
			System.out.println("successful");
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	public void start() {
		Scanner in=new Scanner(System.in);
		try {
			
			OutputStream out=socket.getOutputStream();
			PrintWriter pw=new PrintWriter(
				new OutputStreamWriter(out,"UTF-8"),true);
			pw.println(in.nextLine());//nickname
			new Thread(new serverhandler()).start();
			while (true) {
				
				pw.println(in.nextLine());
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		new newclient().start();
	}
	class serverhandler implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				InputStream in=socket.getInputStream();
				InputStreamReader isr=new InputStreamReader(in,"UTF-8");
				BufferedReader bfr=new BufferedReader(isr);
				while (true) {
					System.out.println(bfr.readLine());
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}

 类似资料: