java socket 编程

自己的入门一点心得。

1:编写一个服务器端,启用10000端口(1024以下端口建议不要使用)。

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

public class Server {
	private ServerSocket ss;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;

	public Server() {
		try {
			ss = new ServerSocket(10000);

			while (true) {
				socket = ss.accept();//此处阻塞等待用户发出请求
				in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));//获得另一方的输入
				out = new PrintWriter(socket.getOutputStream(), true);

				String line = in.readLine();
				System.out.println("you input is :" + line);
				out.println(line);//向另一方发出响应
				out.close();
				in.close();
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				ss.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}finally{
			try {
				ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		new Server();
	}
}

2:编写一个客户端,用来连接刚才我们建立的服务器10000端口

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

public class Client {
	Socket socket;
	BufferedReader in;
	PrintWriter out;

	public Client() {
		try {
			socket = new Socket("192.168.1.78", 10000);//正式获取链接
			out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader line = new BufferedReader(new InputStreamReader(
					System.in));
			out.println(line.readLine());//向另一方发出输入的信息
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));//获得另一方的输入
			String lines = in.readLine();
			System.out.println(lines);
			line.close();
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new Client();
	}
}

 如此 先启用服务器端,然后再启动客户端,在客户端控制台输入内容,回车后服务器端就能收到,然后会发出相应给客户端。

 

3:下面来编写一个服务端,可以接收到多个客户端的链接请求。

     思路如下:

      一:启动一个10000端口 accept方法等待客户端的接入

      二: 接入后将这个链接交给一个线程来管理

     代码如下:

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class OneServer {

	protected  static final int  PORT = 10000;//端口
	
	private ServerSocket ss ;
	private Socket socket;
	public OneServer(){
		try {
			ss = new ServerSocket(10000);//启用10000端口
			while(true){
				socket = ss.accept();//阻塞等待客户端发起链接
				new CreateServerThread(socket);//将链接交给一个线程去管理
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	class CreateServerThread extends Thread{
		private Socket client;
		
		private BufferedReader in;
		private PrintWriter out; 
		
		public CreateServerThread(Socket socket){
			client = socket;
			try{
				in = new BufferedReader(new InputStreamReader(client.getInputStream()));
				out = new PrintWriter(client.getOutputStream(), true); 
				System.out.println("begin........");
				start();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		@Override
		public void run() {
			try {
				String line = in.readLine();//获取对方输入
				System.out.println("用户输入 :"+line);
				while(!"bye".equals(line)){
					String msg = line;
					out.println(msg);
				}
				out.println("bye bye");
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	public static void main(String[] args) {
		new OneServer();
	}
}

 4:下面我们来编写一个类似聊天室的服务器,接收多个客户端的接入,并接收客户端发来的信息同时将信息广播给其他在线的用户。

       思路如下:

        每个接进来的客户链接线程都放入到一个公共的集合来管理,每个客户端发来的消息都放入到一个链表中管理。服务端线程循环读取消息集合,并循环客户端链接进程集合,向各个进程集合发送消息队列中的信息。

        客户端实时读取服务端发来的消息。

        代码如下

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;



/**
 * 聊天室
 * 1 声明几个公共变量集合
 * 2 将消息和用户列表以及每个客户端发起的链接线程都放入到对应的集合中
 * 3   
 * @author Administrator
 *
 */
public class ChatRoom extends ServerSocket 
{

	public ChatRoom() throws IOException {
		super(10000);
		new Broadcast();
		
		while(true){
			Socket socket = accept(); 
			new CreateServerThread(socket);
		}
	}

	private LinkedList<String> messageList = new LinkedList<String>();//存放消息的集合
	private List<CreateServerThread> threadList = new ArrayList<CreateServerThread>();//存放各客户端的线程集合
	private List<String> userList = new ArrayList<String>();
	/**
	 * 内部类 向各个线程进行广播
	 * @author Administrator
	 *
	 */
	class Broadcast extends Thread{

		public Broadcast(){
			start();
		}
		public void run() {
			while(true){
				System.out.println("现在开始进行广播 "+threadList.size());
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(messageList.size()>0){//若集合中有消息 则向用户进行广播
					String message = messageList.getFirst();//或得到最后一个用户发的消息
					if(threadList.size()>0){
						for(CreateServerThread thread : threadList){
							System.out.println(thread+" : "+message);
							thread.sendMessage(message);//向各个在线用户进行广播
						}
						messageList.removeFirst();
					}
				}
			}
		}
	}
	
	/**
	 * 内部类 处理单个线程 用户会话
	 * @author Administrator
	 *
	 */
	class CreateServerThread extends Thread{
		private Socket client;
		private BufferedReader in; 
		private PrintWriter out; 
		
		public CreateServerThread(Socket s){
			client = s;
			try{
				in = new BufferedReader(new InputStreamReader(client.getInputStream()));
				out = new PrintWriter(client.getOutputStream(),true);
				out.println("----welCome to my chatRoom please input your username----");
				start();
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
			}
		}
		
		public void run() {
			try {
				int flag = 0;
				String username = "";
				String line = in.readLine();//得到用户的输入
				System.out.println("get the user input "+line);
				while(!"bye".equals(line)){
					if("show users".equals(line)){//展示用户信息
						out.println(showUsers());
					}else{
						if(flag++ == 0){//说明用户是第一次进入
							threadList.add(this);
							userList.add(line);
							username = line;
							pushMessage(username+" come in ");
						}else{//用户已经输入了用户名 此时状态时用户在聊天 
							pushMessage(username+" : "+line);
						}
					}
					line = in.readLine();
				}
					out.println("bye bye!!");
					userList.remove(username);
					threadList.remove(this);
					pushMessage(username+" leave ");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		private void sendMessage(String str){
			out.println(str);
		}
		private String showUsers(){
			String users = "now there has "+userList.size()+" user is online \n";
			if(userList.size()>0){
				for(String name : userList){
					users +="[ "+name+" ] \n";
				}
			}
			return users;
		}
		
		
		private void pushMessage(String str){
			messageList.addLast(str);
		}
		
	}
	
	
	public static void main(String[] args) throws IOException {
		new ChatRoom();
	}
	
}

你可能感兴趣的:(java,socket)