码迷,mamicode.com
首页 > 编程语言 > 详细

一个简单Java多线程的应用

时间:2018-09-28 12:40:38      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:inpu   一个   []   orm   socket   tao   import   tar   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多线程的应用

标签:inpu   一个   []   orm   socket   tao   import   tar   system   

原文地址:https://www.cnblogs.com/jaffee-L/p/9717291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!