Created
April 14, 2021 14:02
-
-
Save ishanExtreme/e6fae40c6166d86dd6a6b5927afb41de to your computer and use it in GitHub Desktop.
WriteThread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Console; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.io.PrintWriter; | |
import java.net.Socket; | |
/** | |
* Seperate thread for writing the message | |
*/ | |
public class WriteThread extends Thread { | |
private PrintWriter writer; | |
private Socket socket; | |
private Client client; | |
public WriteThread(Socket socket, Client client) { | |
this.socket = socket; | |
this.client = client; | |
try { | |
OutputStream output = socket.getOutputStream(); | |
writer = new PrintWriter(output, true); | |
} catch (IOException ex) { | |
System.out.println("Error getting output stream: " + ex.getMessage()); | |
ex.printStackTrace(); | |
} | |
} | |
@Override | |
public void run() { | |
Console console = System.console(); | |
// First Input is Name | |
String userName = console.readLine("\nEnter your name: "); | |
client.setUserName(userName); | |
writer.println(userName); | |
String text; | |
while (!socket.isOutputShutdown()) { | |
// Send message to socket's output stream | |
text = console.readLine(":"); | |
writer.println(text); | |
} | |
try { | |
socket.close(); | |
writer.close(); | |
} catch (IOException ex) { | |
System.out.println("Error writing to server: " + ex.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment