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

java : chat 客户端

程序员文章站 2022-03-04 15:16:45
...
Client.java
import java.io.*;
import java.net.*;
import java.util.*;

public class Client {
	private String host;
	private int port;

	// 构造方法
	public Client(String host,int port){
		this.host=host;
		this.port=port;
	}
	// 连接方法
	public String connect(String msg){
		if (msg == null) return null;
		StringBuffer sb = new StringBuffer(100);
		try {
			Socket socket = new java.net.Socket(host,port);
        	PrintWriter writer = new java.io.PrintWriter(socket.getOutputStream(),true);
        	writer.println(msg);
        	try {
            	Scanner ins = new java.util.Scanner(socket.getInputStream());
            	while( ins.hasNextLine()){
                	sb.append(ins.nextLine());
            	}
        	} finally {
            	socket.close();
        	}
    	} catch(IOException e){
        	return e.toString();
    	}
    	return sb.toString();
    }
    // Test
    public static void main(String[] args){
    	String msg =null;
    	if (args.length ==1){
    		msg = args[0];
    	} else {
    		System.out.println(" usage: java Clinet message ");
    		System.exit(1);
		}
		String host ="127.0.0.1";
		int port = 12345;
		Client client = new Client(host,port);
		String str = client.connect(msg);
		System.out.println(str);
	}	
			
}

运行 java Client message
相关标签: java chat client