⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clientsocket.java

📁 一个基于java的局域网聊天程序
💻 JAVA
字号:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
	
	/**端口号*/
	private int port = 1704;
	
	/**TCP通信对象*/
	private Socket socket = null;
	private String name;//设置此socket的名字,即用户名
	private String hostIp="localhost";
	public ClientSocket(String str) throws UnknownHostException, IOException {
		socket = new Socket(hostIp,port);
		this.name=str;
	}
	
	public Socket getSocket() {
		return this.socket;//得到这个socket
	}
	
	private PrintWriter getWriter(Socket socket) throws IOException {
		return new PrintWriter(socket.getOutputStream(), true);
	}
	
	private BufferedReader getReader(Socket socket) throws IOException {
		return new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}
	public void setName(String name) {
		this.name=name;
	}
	public String getName() {
		return this.name;
	}
	public void sendName() throws IOException {
		PrintWriter pw = getWriter(socket);
		pw.println(this.getName());
	}
	
	public void talk() throws IOException {
		try {
		PrintWriter pw = getWriter(socket);
		BufferedReader br = getReader(socket);
		
		BufferedReader inputBr = new BufferedReader(new InputStreamReader(System.in));
		pw.println(this.getName());
		//pw.flush();
		String tmp = null;
		while((tmp = inputBr.readLine()) != null) {
			pw.println(tmp);
			String talkStr = br.readLine();
			System.out.println(talkStr);
		}
		} finally {
			if(socket != null) {
				socket.close();
			}
		}
		
	}
	
	public static void main(String args[]) throws UnknownHostException, IOException {
		ClientSocket clientSocket = new ClientSocket("夏靖");
		clientSocket.sendName();
		clientSocket.talk();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -