SOCKET_여러 사람의 채 팅 을 간단하게 실현 하 다.

6126 단어 socket
서버:
package com.kk.review;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

class Server extends Thread{
static List<Socket> online=new ArrayList<Socket>(10);
private Socket socket;
public Server(Socket socket) {
this.socket=socket;
}

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

static void receive(){
try{
ServerSocket server=new ServerSocket(1234);
for (;;) {
Socket socket=server.accept();
new Server(socket).start();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}

@Override
public void run() {
while(true){
try{
online.add(socket);
InputStream in=socket.getInputStream();
byte []buf=new byte[1024];
int len=in.read(buf);
String str=new String(buf,0,len);
for(Socket client:online){
client.getOutputStream().write(str.getBytes());
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}

 
 
클 라 이언 트:
package com.kk.review;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

class Client extends Thread{

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

static void send(){
try{
Socket client=new Socket(InetAddress.getByName(null),1234);
OutputStream out=client.getOutputStream();
new Client().start();
// Scanner input=new Scanner(System.in);
while(true){
Thread.sleep(500);
BufferedReader bis=new BufferedReader(new InputStreamReader(System.in));
String str=bis.readLine();
out.write(str.getBytes());
}
}catch(IOException ioe){
ioe.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void run() {
try{
Socket client=new Socket(InetAddress.getByName(null),1234);
InputStream in=client.getInputStream();
for (;;) {
byte []buf=new byte[1024];
int len=in.read(buf);
String str=new String(buf,0,len);
System.out.println("from server:".concat(str));
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}

좋은 웹페이지 즐겨찾기