一起学习
/**
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();
}
}
}
下载本文示例代码
简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯简单的java socket通讯