java socket 最简单的例子(server 多线程)

server 端

import java.io.*; 
import java.net.*; 
public class Server2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ServerSocket s = null;
        try{
            s= new ServerSocket(5432);
        }
        catch(IOException e)
        {
            System.out.println(e);
            System.exit(1);
        }
        int i = 1;
        while(true)
        {
            
            try{
                Socket cs = s.accept();
                new ServerThread(cs).start();
                System.out.println("接收了 第"+i+"个请求");
                i++;
            }
            catch(IOException e)
            {
                System.out.println(e);
            }
        }
    }

}

serverThread 类

import java.io.*;
import java.net.*;

public class ServerThread extends Thread {
	static String hello = "From Server: Hello world";
	Socket sock;
	public ServerThread(Socket s)
	{
		sock =s ;
	}
	public void run()
	{
		try{
			InputStream in = sock.getInputStream();
			DataInputStream din = new DataInputStream(in);
			String name = din.readUTF();
			OutputStream out = sock.getOutputStream();
			DataOutputStream dos = new DataOutputStream(out);
			dos.writeUTF(hello+"your name :"+name);
			in.close();
			out.close();
			sock.close();
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
	}
}

client 端

import java.io.*; 
import java.net.*; 

public class Client 
{ 

public Client() 
{ 
try 
{ 
Socket s = new Socket("127.0.0.1", 5432); 

OutputStream out = s.getOutputStream(); 

DataOutputStream dout = new DataOutputStream(out);

dout.writeUTF("oftenlin");

InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(in);

String st = din.readUTF();

System.out.println(st);
in.close();
out.close();
s.close(); 
} 
catch (IOException e) 
{} 
} 

public static void main(String[] args) 
{ 
new Client(); 
} 
}
posted @ 2012-12-13 13:17  oftenlin  阅读(11332)  评论(0编辑  收藏  举报