首页 > 程序开发 > 软件开发 > Java >

JAVA中Socket服务器/客户端的通信

2015-06-10

Socket服务器 客户端的通信 (简易) 服务端:接收客户端发来的消息 客户端:接收键盘输入向服务端发送消息 功能简易,其他功能原理相同,只是提供给小代码框架提供出参考 客户端: package co

Socket服务器/客户端的通信
(简易)

服务端:接收客户端发来的消息 客户端:接收键盘输入向服务端发送消息

功能简易,其他功能原理相同,只是提供给小代码框架提供出参考
客户端:
package com.cr.bean;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class client001 {
	@SuppressWarnings("resource")
	public static void main(String []args){
		Scanner scanner = new Scanner(System.in);
		Socket mysocket = null;
		DataInputStream in = null;
		DataOutputStream out = null;
		try {
			mysocket = new Socket();
			System.out.println("请输入服务器IP:");
			String IP = scanner.nextLine();
			System.out.println("请输入端口号:");
			int port = scanner.nextInt();
			if(mysocket.isConnected()){}
			else{
				//连接服务器,使用多线程技术
				InetAddress address = InetAddress.getByName(IP);
				InetSocketAddress socketAddress = new InetSocketAddress(address,port);
				mysocket.connect(socketAddress);
				System.out.println(socketAddress.toString());
				in = new DataInputStream(mysocket.getInputStream());
				out = new DataOutputStream(mysocket.getOutputStream());
			}	
		} catch (Exception e) {
			System.out.print("服务器连接已断开"+e);
		}
		while(true){
			String str = null;
			try { 
				str = scanner.nextLine();
				out.writeUTF(str);
			} catch (Exception e) {
				System.exit(0);
			}
		}
	}
}


服务端:
package com.cr.bean;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class serve001 {
	@SuppressWarnings("resource")
	public static void main(String[] args){
		ServerSocket server = null;
		Socket you = null;
		
		while(true){
			try {
				server = new ServerSocket(7777);
			} catch (IOException e) {
				System.out.println("正在监听……");
			}
			try {
				you = server.accept();
				System.out.println("客户的地址:"+you.getInetAddress());
			} catch (IOException e) {
				System.out.println("正在等待客户");
			}
			if(you!=null){
				new ServerThread(you).start();//为每个客户启动一个专门的线程
			}
		}
	}
}

class ServerThread extends Thread{
	Socket socket;
	DataOutputStream out = null;
	DataInputStream in = null;
	String s = null;
	ServerThread(Socket t){
		socket = t;
		try {
			out = new DataOutputStream(socket.getOutputStream());
			in = new DataInputStream(socket.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		
			try {
				while(true){
					String str = in.readUTF();
					System.out.println("客户端发送给服务器说:"+str);
				}
			} catch (Exception e) {
				System.out.println("客户离开");
		}
	}
}

运行测试: \\


代码相对基础不给予讲解


相关文章
最新文章
热点推荐