简单的java socket通讯

王朝java/jsp·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

/**

class:SocketTest_SvrClit

author:chengyun

date:

with:to test socket---server program;

**/

import Java.net.*;

import java.io.*;

public class SocketTest_Server

{

public static void main(String[] args) throws UnknownHostException,IOException,ConnectException

{

ServerSocket aServerSocket=new ServerSocket(3434);

Socket aServer=null;

try

{

aServer=aServerSocket.accept();

try

{

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

BufferedReader in=new BufferedReader(new InputStreamReader(aServer.getInputStream()));

PrintWriter out=new PrintWriter(new OutputStreamWriter(aServer.getOutputStream()));

String serverstring=null;

String clientstring=null;

System.out.println("hello! enter the bye to exit.");

System.out.print("Server:wait client");

serverstring=input.readLine();

boolean done=false;

while(!done)

{

if(serverstring !=null)

{

out.println(serverstring);

out.flush();

}

clientstring=in.readLine();

if(clientstring !=null)

System.out.println("client:"+clientstring);

System.out.print("server:");

serverstring=input.readLine();

if(serverstring.equals("bye")) done=true;

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aServer.close();

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aServerSocket.close();

}

}

}

/**

class:SocketTest_SvrClit

author:chengyun

date:

with:to test socket---client program;

**/

import java.net.*;

import java.io.*;

public class SocketTest_SvrClit

{

public static void main(String[] args) throws UnknownHostException,IOException,ConnectException

{

Socket aClient=null;

aClient=new Socket("192.168.0.8",3434); //InetAddress.getLocalHost()

try

{

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

BufferedReader in=new BufferedReader(new InputStreamReader(aClient.getInputStream()));

PrintWriter out=new PrintWriter(new OutputStreamWriter(aClient.getOutputStream()));

String clientString=null;

String serverString=null;

System.out.println("hello!enter bye to exit.");

boolean done=false;

while(!done)

{

serverString=in.readLine();

if(serverString !=null)

System.out.println("Server:"+serverString);

System.out.print("client:");

clientString=input.readLine();

if(clientString.equals("bye")) done=true;

if(clientString !=null)

{

out.println(clientString);

out.flush();

}

}

in.close();

out.close();

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

finally

{

aClient.close();

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航