Created
November 11, 2014 09:07
-
-
Save AmirHooshangi/feb7dc3d30ea46653cf1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.BufferedInputStream; | |
import java.io.DataInputStream; | |
import java.io.DataOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.net.Socket; | |
public class Client { | |
Socket socket = null; | |
DataOutputStream os = null; | |
DataInputStream is = null; | |
public void initializeSocket() throws IOException { | |
socket = new Socket("localhost", 9090); | |
os = new DataOutputStream(socket.getOutputStream()); | |
is = new DataInputStream(socket.getInputStream()); | |
} | |
public void sendText(String text) throws IOException { | |
os.writeBoolean(true); | |
os.writeChars(text); | |
} | |
public String getTextFromServer() throws InterruptedException, IOException { | |
Thread.sleep(1000); | |
if (is.available() > 0) { | |
return is.readUTF(); | |
} else { | |
return ""; | |
} | |
} | |
public void sendFile(File file) throws IOException { | |
os.writeBoolean(false); | |
byte[] mybytearray = new byte[(int) file.length()]; | |
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); | |
bis.read(mybytearray, 0, mybytearray.length); | |
os.write(mybytearray, 0, mybytearray.length); | |
os.flush(); | |
} | |
public static void main(String[] args) throws IOException, InterruptedException { | |
Client client = new Client(); | |
client.initializeSocket(); | |
client.sendText("salaaaaam"); | |
System.out.println(client.getTextFromServer()); | |
client.sendFile(new File("/Users/amir/Desktop/gate.txt")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment