Skip to content

Instantly share code, notes, and snippets.

@hkulekci
Created May 15, 2011 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkulekci/973563 to your computer and use it in GitHub Desktop.
Save hkulekci/973563 to your computer and use it in GitHub Desktop.
Communication with Socket Connection
package socketprogramming;
/**
*
* @author kulekci
*/
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class client
{
//http://www.calsoftlabs.com/whitepapers/java-networking.html
public static String [] text = null;
public static void readFile(){
try{
FileInputStream fstream = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int i = 0;
while ((strLine = br.readLine()) != null) {
text[i++] = strLine;
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String args[])
{
Socket sock=null;
DataInputStream dis=null;
PrintStream ps=null;
System.out.println(" Trying to connect");
try
{
InetAddress ip =InetAddress.getByName
("192.168.2.5");
readFile();
sock= new Socket(ip,Server.PORT);
ps= new PrintStream(sock.getOutputStream());
if (text != null){
for (int i = 0; i<text.length;i++){
ps.println(text[i]);
}
}
DataInputStream is = new
DataInputStream(sock.getInputStream());
System.out.println(is.readLine());
}
catch(SocketException e)
{
System.out.println("SocketException " + e);
}
catch(IOException e)
{
System.out.println("IOException " + e);
}
finally
{
try
{
sock.close();
}
catch(IOException ie)
{
System.out.println(" Close Error :" +
ie.getMessage());
}
}
}
}
package socketprogramming;
import java.io.*;
import java.net.*;
/**
*
* @author kulekci
*/
public class Server{
//port number should be more than 1024
public static final int PORT = 1025;
public static void main( String args[])
{
ServerSocket sersock = null;
Socket sock = null;
System.out.println(" Wait !! ");
try
{
sersock = new ServerSocket(PORT);
System.out.println("Server Started :"+sersock);
try
{
while (true){
sock = sersock.accept();
System.out.println("Client Connected :"+ sock);
DataInputStream ins = new DataInputStream(sock.getInputStream());
PrintStream ios = new PrintStream(sock.getOutputStream());
ios.println("data_accepted");
ios.close();
sock.close();
}
}catch(SocketException se){
System.out.println("Server Socket problem "+se.getMessage());
}
}catch(Exception e){
System.out.println("Couldn't start "
+ e.getMessage()) ;
}
System.out.println(" Connection from : " + sock.getInetAddress());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment