欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

chat客户端

程序员文章站 2022-03-15 21:57:48
...
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();
			}
			
		}
		
	}
}

相关标签: tcp