برنامج خطير يرسل من الكلاينت الى السيرفر انتقر كود الكلاينت هو import java.net.*;
import java.io.*;
public class TCPClient {
public static void main (String args[]) {
// arguments supply message and hostname of destination
Socket s = null;
try{
int serverPort = 7896;
s = new Socket("127.0.0.1", serverPort);
DataInputStream in = new DataInputStream( s.getInputStream());
DataOutputStream out =
new DataOutputStream( s.getOutputStream());
out.writeUTF("127.0.0.1"); // UTF is a string encoding see Sn 4.3
System.out.println("Enter message:");
int m = System.in.read();
String data = in.readUTF();
System.out.println(m+"\n"+data) ;
}catch (UnknownHostException e){
System.out.println("Sock:"+e.getMessage());
}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
}catch (IOException e){System.out.println("IO:"+e.getMessage());}
finally {if(s!=null) try {s.close();}catch (IOException e){System.out.println("close:"+e.getMessage());}}
}
}
وكود السيرفر هو
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main (String args[]) {
try{
int serverPort = 7896;
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true) {
Socket clientSocket = listenSocket.accept();
Connection c = new Connection(clientSocket);
}
} catch(IOException e) {System.out.println("Listen :"+e.getMessage());}
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection (Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream( clientSocket.getInputStream());
out =new DataOutputStream( clientSocket.getOutputStream());
this.start();
} catch(IOException e) {System.out.println("Connection:"+e.getMessage());}
}
public void run(){
try { // an echo server
String data = in.readUTF();
out.writeUTF(data);
} catch(EOFException e) {System.out.println("EOF:"+e.getMessage());
} catch(IOException e) {System.out.println("IO:"+e.getMessage());}
finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}
}
}
// this figure continues on the next slide
السوال هل تستطيع تحويله الى كاركتر حاول