Write a TCP program for chat application.
TCP Client:
import java.io.*;
import java.net.*;
import java.util.*;
class TCPClientChat {
public static void main(String[] args) {
try {
Socket port = new Socket("Localhost", 9876);
InputStream receivingMessage = port.getInputStream();
OutputStream sendingMsg = port.getOutputStream();
DataInputStream receiveDataMsg = new DataInputStream(receivingMessage);
DataOutputStream sendDataMsg = new DataOutputStream(sendingMsg);
Scanner sc = new Scanner(System.in);
while(1==1) {
System.out.print("Client: ");
String sndMsg = sc.nextLine();
sendDataMsg.writeUTF(sndMsg);
String rcvMsg = receiveDataMsg.readUTF();
System.out.println("Server: " + rcvMsg);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
TCP Server:
import java.io.*;
import java.net.*;
import java.util.*;
class TCPServerChat {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(9876);
Socket port = server.accept();
InputStream receivingMessage = port.getInputStream();
OutputStream sendingMsg = port.getOutputStream();
DataInputStream receiveDataMsg = new DataInputStream(receivingMessage);
DataOutputStream sendDataMsg = new DataOutputStream(sendingMsg);
Scanner sc = new Scanner(System.in);
while(1==1) {
String rcvMsg = receiveDataMsg.readUTF();
System.out.println("Client: " + rcvMsg);
System.out.print("Server: ");
String sndMsg = sc.nextLine();
sendDataMsg.writeUTF(sndMsg);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
0 Comments