java : chat 客户端_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java : chat 客户端

java : chat 客户端

 2018/8/25 15:35:25  belldeep  程序员俱乐部  我要评论(0)
  • 摘要:Client.javaimportjava.io.*;importjava.net.*;importjava.util.*;publicclassClient{privateStringhost;privateintport;//构造方法publicClient(Stringhost,intport){this.host=host;this.port=port;}//连接方法publicStringconnect(Stringmsg){if(msg==null)returnnull
  • 标签:Java 客户 客户端
Client.java
class="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
发表评论
用户名: 匿名