1. 程式人生 > >一個簡單Java多線程的應用

一個簡單Java多線程的應用

accept NPU from rop import ati .get bytes system

import java.net.*;
import java.io.*;
public class simpleServer
{
private static ServerSocket serverSocket;
private static listenClient listen;
public static void main(String[] args) throws Exception
{
int port;
if(args.length==0)
{
System.out.println(‘Usage:java simpleServer [port]‘);
System.exit(1);
}
port=Integer.parseInt(args[0]);
startServer(port);
}
public static void startServer(int port)throws Exception
{
try
{
serverSocket=new ServerSocket(port);
Thread thread=new Thread(new listenClient(serverSocket));
thread.start();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
class listenClient implements Runnable
{
private ServerSocket serverSocket;
private Socket clientSocket;
DataInputStream in;
DataOutputStream out;
public listenClient(ServerSocket ser verSocket)throws Exception
{
this.serverSocket=serverSocket;
}
public void run()
{
try
{
while(true)
{
clientSocket=serverSocket.accept();
System.out.println(‘Connection from ‘+clientSocket.getInetAddress().getHostAddress());
in=new DataInputStream(clientSocket.getInputStream());
out=new DataOutputStream(clientSocket.getOutputStream());
String lineSep=System.getProperty(‘line.separator‘);//行分隔符,即回車換行
InetAddress addr=serverSocket.getInetAddress().getLocalHost();
String outData=‘Server Information: ‘+lineSep+‘ Local Host: ‘+serverSocket.getInetAddress().getLocalHost()+lineSep+‘ port :‘+serverSocket.getLocalPort();
byte[] outByte=outData.getBytes();
out.write(outByte,0,outByte.length);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
};
import java.net.*;
import java.io.*;
public class simpleClient
{
private staticSocket socket;
public static void main(String[] args)throws Exception
{
String host;
int port;
if(args.length <2)
{
System.out.println(‘Usage:java simpleClient [remote IP/Host] [port]‘);
System.exit(1);
}
host=args[0];
port=Integer.parseInt(args[1]);
connectServer(host,port);
}
public static void connectServer(String host,int port)
{
try
{
socket=new Socket(InetAddress.getByName(host),port);
DataInputStream in=new DataInputStream(socket.getInputStream());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
byte[] inByte=new byte[1024];
in.read(inByte);
String response=new String(inByte,0,inByte.length);
System.out.println(‘Message from server: ‘);
System.out.println(response.trim());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

一個簡單Java多線程的應用