码迷,mamicode.com
首页 > 其他好文 > 详细

一个简单的Socket通信Demo

时间:2015-06-11 10:57:15      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

都忘了哪里下的了,留个记录

服务器端Demo:

Server.java(服务器端运行主程序,直接运行):

package cn.wjs;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static final int port = 9999;
	private static final int backlog = 100;
	private static final String bindAddr = "127.0.0.1";

	public static void main(String[] args) throws Exception {
		System.out.println("正在启动Socket服务器");

		ServerSocket server = new ServerSocket(9998, 100, InetAddress.getByName("127.0.0.1"));
		System.out.println("启动完成\n正在监听客户端连接");
		while (true) {
			Socket socket = server.accept();
			System.out.println("产生了一个新的会话,来自:" + socket.getInetAddress() + "\n==================================");
			new ServerMessageReceiver(socket).start();
			new ServerMessageSender(socket).start();
			System.out.println("服务器端已启动");
		}
	}
}

ServerMessageReceiver.java:

package cn.wjs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ServerMessageReceiver extends Thread
{
  private Socket socket;

  public ServerMessageReceiver(Socket socket)
  {
    this.socket = socket;
  }

  public void run() {
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));

      String content = null;
      while (true) {
        if (this.socket.isClosed()) {
          System.out.println("Socket已经关闭");
          reader.close();
          this.socket.close();
          break;
        }
        content = reader.readLine();
        if (content.equals("bye")) {
          System.out.println("对方请求关闭连接,无法继续进行聊天");
          reader.close();
          this.socket.close();
          break;
        }
        System.out.println("【对方】" + content + "\n");
      }
      reader.close();
      this.socket.close();
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ServerMessageSender.java:

package cn.wjs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ServerMessageSender extends Thread
{
  private Socket socket;

  public ServerMessageSender(Socket socket)
  {
    this.socket = socket;
  }

  public void run() {
    try {
      BufferedWriter outwriter = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8"));
      BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
      String msg = null;
      while (true) {
        msg = inputReader.readLine();
        if (msg.toLowerCase().equals("exit")) {
          System.exit(0);
        }
        if (this.socket.isClosed()) {
          System.out.println("Socket已经关闭");
          outwriter.close();
          inputReader.close();
          this.socket.close();
          break;
        }
        outwriter.write(msg);
        outwriter.newLine();
        outwriter.flush();
      }
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ClientDemo:

Client.java(客户端主程序,直接运行):

package cn.wjs;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client
{
  private static final int port = 9999;
  private static final String bindAddr = "127.0.0.1";

  public static void main(String[] args)
  {
    System.out.println("正在连接Socket服务器");
    try {
      Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9998);
      System.out.println("已连接\n================");
      new ClientMessageSender(socket).start();
      new ClientMessageReceiver(socket).start();
      System.out.println("已启动");
    }
    catch (UnknownHostException e) {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ClientMessageReceiver.java:

package cn.wjs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ClientMessageReceiver extends Thread
{
  private Socket socket;

  public ClientMessageReceiver(Socket socket)
  {
    this.socket = socket;
  }

  public void run()
  {
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
      String content = null;
      while (true) {
        if (this.socket.isClosed()) {
          System.out.println("Socket已经关闭");
          reader.close();
          this.socket.close();
          break;
        }
        content = reader.readLine();
        if (content.equals("bye")) {
          System.out.println("对方请求关闭连接,无法继续进行聊天");
          reader.close();
          this.socket.close();
          break;
        }
        System.out.println("【对方】" + content + "\n");
      }
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ClientMessageSender.java:

package cn.wjs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ClientMessageSender extends Thread
{
  private Socket socket;

  public ClientMessageSender(Socket socket)
  {
    this.socket = socket;
  }

  public void run()
  {
    try {
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8"));
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String msg = null;
      while (true) {
        msg = reader.readLine();
        if (msg.toLowerCase().equals("exit")) {
          System.exit(0);
        }
        if (this.socket.isClosed()) {
          System.out.println("Socket已经关闭");
          writer.close();
          this.socket.close();
          break;
        }
        writer.write(msg);
        writer.newLine();
        writer.flush();
      }
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 

通过elicpse导出jar包直接运行,服务器端导出jar设置main.class为Server.java,客户端导出jar设置main.class为Client.java

 

一个简单的Socket通信Demo

标签:

原文地址:http://www.cnblogs.com/wujinsen/p/4568252.html

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