package multithreading;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
//Accouding to the headfirst java appendix A's codes and created by BirdKing2006 2008-2-26
//运用技术:Swing,Socket,multithreading,泛形
//客户端程序
public class BeatBoxFinal {
JFrame theFrame;
JPanel mainPanel;
JList incomingList;
JTextField userMessage;
ArrayList<JCheckBox> checkboxList;
int nextNum;
Vector<String> listVect = new Vector<String>();
String userName;
ObjectOutputStream out;
ObjectInputStream in;
HashMap<String,boolean[]> otherSeqsMap = new HashMap<String,boolean[]>();
Sequencer sequencer;
Sequence sequence;
Sequence mySequence = null;
Track track;
String[] instrumentNames = {"Bass Drum","Closed Hi-Hat","Open Hi-Hat","Acoustic Snare","Crash Cymbal",
"Hand Clap","High Tom","Hi Bongo","Maracas","Whistle","Low Conga","Cowbell","Vibraslap","Low-mid Tom",
"High Agogo","Open Hi Conga"};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
public static void main(String[] args) {
new BeatBoxFinal().startUp(args[0]);
}
public void startUp(String name){
userName = name;
//open connection to the server
try{
Socket sock = new Socket("127.0.0.1",4242);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Thread remote = new Thread(new RemoteReader());
remote.start();
}catch(Exception ex){
ex.printStackTrace();
}
setUpMidi();
buildGui();
}
/**
*
*/
public void buildGui(){
theFrame = new JFrame("Cyber BeatBox");
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton("Start");
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop = new JButton("Stop");
start.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton("Tempo Up");
start.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton("Tempo Down");
start.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
JButton sendIt = new JButton("sendIt");
start.addActionListener(new MySendListener());
buttonBox.add(sendIt);
userMessage = new JTextField();
buttonBox.add(userMessage);
incomingList = new JList();
incomingList.addListSelectionListener(new MyListSelecttionListener());
incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane theList = new JScrollPane(incomingList);
buttonBox.add(theList);
incomingList.setListData(listVect);
Box nameBox = new Box(BoxLayout.Y_AXIS);
for(int i=0;i<16;i++){
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.EAST,buttonBox);
background.add(BorderLayout.WEST,nameBox);
theFrame.getContentPane().add(background);
GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER,mainPanel);
for(int i=0;i<256;i++){
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
}
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
}
public void setUpMidi(){
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
} catch (Exception e) {
e.printStackTrace();
}
}
public void buildTrackAndStart(){
ArrayList<Integer> trackList = null; //this will hold the instruments for each
sequence.deleteTrack(track);
track = sequence.createTrack();
for(int i=0;i<16;i++){
trackList = new ArrayList<Integer>();
for(int j=0;j<16;j++){
JCheckBox jc = (JCheckBox)checkboxList.get(j+(16*i));
if(jc.isSelected()){
int key = instruments[i];
trackList.add(new Integer(key));
}else{
//because this slod shoud be empty in the track
trackList.add(null);
}
}
makeTracks(trackList);
}
track.add(makeEvent(192,9,1,0,15));
try{
sequencer.setSequence(sequence);
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
}catch(Exception e){
e.printStackTrace();
}
}
public class MyStartListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
buildTrackAndStart();
}
}
public class MyStopListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
sequencer.stop();
}
}
public class MyUpTempoListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
float tempoFactor = sequencer.getTempoFactor();
//设置速度,以每四分音符的微秒数为单位。实际的回放速度是指定值和速度因子的乘积。
sequencer.setTempoFactor((float)(tempoFactor*1.03));
}
}
public class MyDownTempoListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor*0.97));
}
}
boolean[] checkboxState = new boolean[256];
public class MySendListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//make an arrayList of just the STATE of the checkboxes
//boolean型数据默认为false
for(int i=0;i<256;i++){
JCheckBox check = (JCheckBox)checkboxList.get(i);
if(check.isSelected()){
checkboxState[i] = true;
}
}
String messageToSend = null;
try {
nextNum++;
out.writeObject(userName+nextNum+": "+userMessage.getText());
out.writeObject(checkboxState);
} catch (Exception exe) {
exe.printStackTrace();
}
userMessage.setText("");
}
}
//this method is called when the user selects something from the list
//we Immediately change the pattern to the one they selected
public void changeSequnce(boolean[] selectedState){
for(int i=0;i<256;i++){
JCheckBox check = (JCheckBox)checkboxList.get(i);
if(checkboxState[i]){
check.setSelected(true);
}else{
check.setSelected(false);
}
}
}
public class MyListSelecttionListener implements ListSelectionListener{
public void valueChanged(ListSelectionEvent e) {
//如果是单选
if(!e.getValueIsAdjusting()){
String selected = (String)incomingList.getSelectedValue();
if(selected != null){
//now go to the map,and change the sequnce
boolean[] selectedState = (boolean[])otherSeqsMap.get(selected);
changeSequnce(selectedState);
sequencer.stop();
buildTrackAndStart();
}
}
}
}
public void makeTracks(ArrayList list){
Iterator it = list.iterator();
for(int i=0;i<16;i++){
Integer num = (Integer)it.next();
if(num!=null){
int numValue = num.intValue();
track.add(makeEvent(144,9,numValue,100,i));
track.add(makeEvent(128,9,numValue,100,i+1));
}
}
}
public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd,chan,one,two);
event = new MidiEvent(a,tick);
} catch (Exception e) {
e.printStackTrace();
}
return event;
}
public class RemoteReader implements Runnable{
boolean[] checkboxState = null;
String nameToShow = null;
Object obj = null;
public void run() {
try {
while((obj=in.readObject()) != null){
System.out.println("got an object from server");
System.out.println(obj.getClass());
nameToShow = (String)obj;
checkboxState = (boolean[])in.readObject();
otherSeqsMap.put(nameToShow,checkboxState);
listVect.add(nameToShow);
incomingList.setListData(listVect);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
---------------------------------------------------------------分隔线----------------------------------------------------------------------
package multithreading;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
//服务器端程序
public class MusicServer {
ArrayList<ObjectOutputStream> clientOutputStreams;
public static void main(String[] args) {
new MusicServer().go();
}
public class ClientHander implements Runnable{
ObjectInputStream in;
Socket clientSocket;
public ClientHander(Socket socket){
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public void run(){
Object o1 = null;
Object o2 = null;
try {
while((o1 = in.readObject()) != null){
o2 = in.readObject();
System.out.println("read two objects!");
tellEveryone(o1,o2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void go(){
clientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSocket = new ServerSocket(4242);
while(true){
Socket clientSocket = serverSocket.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
clientOutputStreams.add(out);
Thread t = new Thread(new ClientHander(clientSocket));
t.start();
System.out.println("got a connection!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void tellEveryone(Object o1,Object o2){
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()){
try{
ObjectOutputStream out = (ObjectOutputStream)it.next();
out.writeObject(o1);
out.writeObject(o2);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
//Accouding to the headfirst java appendix A's codes and created by BirdKing2006 2008-2-26
//运用技术:Swing,Socket,multithreading,泛形
//客户端程序
public class BeatBoxFinal {
JFrame theFrame;
JPanel mainPanel;
JList incomingList;
JTextField userMessage;
ArrayList<JCheckBox> checkboxList;
int nextNum;
Vector<String> listVect = new Vector<String>();
String userName;
ObjectOutputStream out;
ObjectInputStream in;
HashMap<String,boolean[]> otherSeqsMap = new HashMap<String,boolean[]>();
Sequencer sequencer;
Sequence sequence;
Sequence mySequence = null;
Track track;
String[] instrumentNames = {"Bass Drum","Closed Hi-Hat","Open Hi-Hat","Acoustic Snare","Crash Cymbal",
"Hand Clap","High Tom","Hi Bongo","Maracas","Whistle","Low Conga","Cowbell","Vibraslap","Low-mid Tom",
"High Agogo","Open Hi Conga"};
int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
public static void main(String[] args) {
new BeatBoxFinal().startUp(args[0]);
}
public void startUp(String name){
userName = name;
//open connection to the server
try{
Socket sock = new Socket("127.0.0.1",4242);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Thread remote = new Thread(new RemoteReader());
remote.start();
}catch(Exception ex){
ex.printStackTrace();
}
setUpMidi();
buildGui();
}
/**
*
*/
public void buildGui(){
theFrame = new JFrame("Cyber BeatBox");
BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_AXIS);
JButton start = new JButton("Start");
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop = new JButton("Stop");
start.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton upTempo = new JButton("Tempo Up");
start.addActionListener(new MyUpTempoListener());
buttonBox.add(upTempo);
JButton downTempo = new JButton("Tempo Down");
start.addActionListener(new MyDownTempoListener());
buttonBox.add(downTempo);
JButton sendIt = new JButton("sendIt");
start.addActionListener(new MySendListener());
buttonBox.add(sendIt);
userMessage = new JTextField();
buttonBox.add(userMessage);
incomingList = new JList();
incomingList.addListSelectionListener(new MyListSelecttionListener());
incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane theList = new JScrollPane(incomingList);
buttonBox.add(theList);
incomingList.setListData(listVect);
Box nameBox = new Box(BoxLayout.Y_AXIS);
for(int i=0;i<16;i++){
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.EAST,buttonBox);
background.add(BorderLayout.WEST,nameBox);
theFrame.getContentPane().add(background);
GridLayout grid = new GridLayout(16,16);
grid.setVgap(1);
grid.setHgap(2);
mainPanel = new JPanel(grid);
background.add(BorderLayout.CENTER,mainPanel);
for(int i=0;i<256;i++){
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
}
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
}
public void setUpMidi(){
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ,4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
} catch (Exception e) {
e.printStackTrace();
}
}
public void buildTrackAndStart(){
ArrayList<Integer> trackList = null; //this will hold the instruments for each
sequence.deleteTrack(track);
track = sequence.createTrack();
for(int i=0;i<16;i++){
trackList = new ArrayList<Integer>();
for(int j=0;j<16;j++){
JCheckBox jc = (JCheckBox)checkboxList.get(j+(16*i));
if(jc.isSelected()){
int key = instruments[i];
trackList.add(new Integer(key));
}else{
//because this slod shoud be empty in the track
trackList.add(null);
}
}
makeTracks(trackList);
}
track.add(makeEvent(192,9,1,0,15));
try{
sequencer.setSequence(sequence);
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
}catch(Exception e){
e.printStackTrace();
}
}
public class MyStartListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
buildTrackAndStart();
}
}
public class MyStopListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
sequencer.stop();
}
}
public class MyUpTempoListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
float tempoFactor = sequencer.getTempoFactor();
//设置速度,以每四分音符的微秒数为单位。实际的回放速度是指定值和速度因子的乘积。
sequencer.setTempoFactor((float)(tempoFactor*1.03));
}
}
public class MyDownTempoListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor*0.97));
}
}
boolean[] checkboxState = new boolean[256];
public class MySendListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//make an arrayList of just the STATE of the checkboxes
//boolean型数据默认为false
for(int i=0;i<256;i++){
JCheckBox check = (JCheckBox)checkboxList.get(i);
if(check.isSelected()){
checkboxState[i] = true;
}
}
String messageToSend = null;
try {
nextNum++;
out.writeObject(userName+nextNum+": "+userMessage.getText());
out.writeObject(checkboxState);
} catch (Exception exe) {
exe.printStackTrace();
}
userMessage.setText("");
}
}
//this method is called when the user selects something from the list
//we Immediately change the pattern to the one they selected
public void changeSequnce(boolean[] selectedState){
for(int i=0;i<256;i++){
JCheckBox check = (JCheckBox)checkboxList.get(i);
if(checkboxState[i]){
check.setSelected(true);
}else{
check.setSelected(false);
}
}
}
public class MyListSelecttionListener implements ListSelectionListener{
public void valueChanged(ListSelectionEvent e) {
//如果是单选
if(!e.getValueIsAdjusting()){
String selected = (String)incomingList.getSelectedValue();
if(selected != null){
//now go to the map,and change the sequnce
boolean[] selectedState = (boolean[])otherSeqsMap.get(selected);
changeSequnce(selectedState);
sequencer.stop();
buildTrackAndStart();
}
}
}
}
public void makeTracks(ArrayList list){
Iterator it = list.iterator();
for(int i=0;i<16;i++){
Integer num = (Integer)it.next();
if(num!=null){
int numValue = num.intValue();
track.add(makeEvent(144,9,numValue,100,i));
track.add(makeEvent(128,9,numValue,100,i+1));
}
}
}
public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd,chan,one,two);
event = new MidiEvent(a,tick);
} catch (Exception e) {
e.printStackTrace();
}
return event;
}
public class RemoteReader implements Runnable{
boolean[] checkboxState = null;
String nameToShow = null;
Object obj = null;
public void run() {
try {
while((obj=in.readObject()) != null){
System.out.println("got an object from server");
System.out.println(obj.getClass());
nameToShow = (String)obj;
checkboxState = (boolean[])in.readObject();
otherSeqsMap.put(nameToShow,checkboxState);
listVect.add(nameToShow);
incomingList.setListData(listVect);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
---------------------------------------------------------------分隔线----------------------------------------------------------------------
package multithreading;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
//服务器端程序
public class MusicServer {
ArrayList<ObjectOutputStream> clientOutputStreams;
public static void main(String[] args) {
new MusicServer().go();
}
public class ClientHander implements Runnable{
ObjectInputStream in;
Socket clientSocket;
public ClientHander(Socket socket){
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public void run(){
Object o1 = null;
Object o2 = null;
try {
while((o1 = in.readObject()) != null){
o2 = in.readObject();
System.out.println("read two objects!");
tellEveryone(o1,o2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void go(){
clientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSocket = new ServerSocket(4242);
while(true){
Socket clientSocket = serverSocket.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
clientOutputStreams.add(out);
Thread t = new Thread(new ClientHander(clientSocket));
t.start();
System.out.println("got a connection!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void tellEveryone(Object o1,Object o2){
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()){
try{
ObjectOutputStream out = (ObjectOutputStream)it.next();
out.writeObject(o1);
out.writeObject(o2);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}