aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/cycling74/net/TcpSender.java
blob: 2ba0f6708db88b2adebd5a4520bb871267342a4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.cycling74.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

import com.cycling74.max.Atom;
import com.cycling74.max.MaxRuntimeException;

/** 
 * This portion of code is scheduled for pdj-0.8.5
 * IT IS NOT FUNCTIONAL
 */
public class TcpSender {
	DatagramSocket sender;
	DatagramPacket packet;
	String address = null;
	int port = -1;
	
	public TcpSender() {
	}
	
	public TcpSender(String address, int port) {
		this.address= address;
		this.port = port;
	}
	
	public void send(Atom args[]) {
		if ( sender == null )
			initsocket();
		
		byte buff[] = Atom.toOneString(args).getBytes();
		packet.setData(buff, 0, buff.length);
		try {
			sender.send(packet);
		} catch (IOException e) {
			throw new MaxRuntimeException(e);
		}
	}
	
	public void send(int i) {
		if ( sender == null )
			initsocket();
		
		byte buff[] = Integer.toString(i).getBytes();
		packet.setData(buff, 0, buff.length);
		try {
			sender.send(packet);
		} catch (IOException e) {
			throw new MaxRuntimeException(e);
		}
	}
	
	public void send(float f) {
		if ( sender == null ) 
			initsocket();
		
		byte buff[] = Float.toString(f).getBytes();
		packet.setData(buff, 0, buff.length);
		try {
			sender.send(packet);
		} catch (IOException e) {
			throw new MaxRuntimeException(e);
		}
	}

	public String getAddress() {
		return address;
	}
	
	public void setAddress(String address) {
		if ( sender != null ) { 
			sender = null;
			sender.close();
		}
		this.address = address;
	}
	
	public int getPort() {
		return port;
	}
	
	public void setPort(int port) {
		if ( sender != null ) {
			sender = null;
			sender.close();
		}
		this.port = port;
	}
	
	private synchronized void initsocket() {
		if ( sender != null )
			return;
		try {
			sender = new DatagramSocket();
			sender.connect(new InetSocketAddress(address, port));
			packet = new DatagramPacket(new byte[0], 0);
		} catch (Exception e) {
			throw new MaxRuntimeException(e);
		}
	}
}