String Concatenation in Java using TCP
This is the Java Program to Concatenate two strings using TCP,the client sends two strings to the server where these two strings are concatenated and sent back to the client
Client Program:
ChatClient.java
import java.io.*;
import java.net.*;
public class ChatClient
{
public static void main(String[] args) throws Exception
{
String Message;
int port=Integer.parseInt(args[1]);
String hostname=args[0];
while(true)
{
Socket client=new Socket(hostname,port);
OutputStream out=client.getOutputStream();
DataOutputStream outt=new DataOutputStream(out);
System.out.println("Enter String 1");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Message=in.readLine();
System.out.println("Enter String 2");
String Message2=in.readLine();
outt.writeUTF(Message);
outt.writeUTF(Message2);
InputStream inn=client.getInputStream();
DataInputStream ins=new DataInputStream(inn);
System.out.println(ins.readUTF());
client.close();
}
}
}
Server Program:
ChatServer.java
import java.io.*;
import java.net.*;
public class ChatServer extends Thread
{
String ServerName,Message;
private ServerSocket server;
public ChatServer(int port) throws Exception
{
server=new ServerSocket(port);
server.setSoTimeout(0);
}
public void run()
{
while(true)
{
try
{
Socket conn = server.accept();
DataInputStream in = new DataInputStream(conn.getInputStream());
String news=in.readUTF();
String news1=in.readUTF();
DataOutputStream out=new DataOutputStream(conn.getOutputStream());
out.writeUTF(news+news1);
conn.close();
}
catch(Exception e){e.printStackTrace();}
}
}
public static void main(String[] args) throws Exception
{
int port=Integer.parseInt(args[0]);
Thread t=new ChatServer(port);
t.start();
}}
Recent Comments