程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 一個Scocket實例程序

一個Scocket實例程序

編輯:關於JAVA

import Java.io.*;

import Java.Net.*;

public class EchoServer1

{ public static void main(String[] args )

{ try

{

ServerSocket s = new ServerSocket(8500);

Socket incoming = s.accept( );

BufferedReader in = new BufferedReader

(new InputStreamReader(incoming.getInputStream()));

PrintWriter out = new PrintWriter

(incoming.getOutputStream(), true /* autoFlush */);

out.println( "Hello! Enter BYE to exit." );

boolean done = false;

while (!done)

{ String line = in.readLine();

if (line == null) done = true;

else

{ out.println("Echo: " + line);

if (line.trim().equals("BYE"))

done = true;

}

}

incoming.close();

}

catch (Exception e)

{ System.out.println(e);

}

}

}

// EchoClIEnt1.Java

import Java.io.*;

import Java.Net.*;

public class EchoClIEnt1 {

public static void main(String args[]) {

try{

if (args.length != 1){

System.out.println("USAGE: Java ClIEnt servername");

return;

}

String connectto= args[0];

Socket connection;

// connect to server

if(connectto.equals("localhost")){

connection=new Socket(InetAddress.getLocalHost(),8500);

}

else{

connection=new Socket(InetAddress.getByName(connectto),8500);

}

BufferedReader input=new BufferedReader(new InputStreamReader(connection.getInputStream()));

PrintWriter out = new PrintWriter(connection.getOutputStream(), true /* autoFlush */);

// read information from server

String info;

info = input.readLine();

System.out.println(info);

boolean done = false;

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String sInput;

while(!done){

sInput = in.readLine();

out.println(sInput);

if (sInput.equalsIgnoreCase("bye")) done = true;

info = input.readLine();

System.out.println(info);

}

connection.close();

}

catch(SecurityException e){

System.out.println("SecurityException when connecting Server!");

}

catch(IOException e){

System.out.println("IOException when connecting Server!");

}

}

}

運行

1 運行服務器

Java EchoServer1

2 運行 客戶端

Java EchoClIEnt1 server_hostname

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved