Jump to content
  • Sky
  • Blueberry
  • Slate
  • Blackcurrant
  • Watermelon
  • Strawberry
  • Orange
  • Banana
  • Apple
  • Emerald
  • Chocolate
  • Charcoal
Congon4tor

TCP Server

Recommended Posts

Had some trouble getting a TCP connection between an OpenComputers program (client) and a java program (server), so I thought I could sare this.

 

Here is the lua program:

--VARIABLES
local event = require("event")
local net = require("internet")
local term = require("term")
local os = require("os")
 
local running = true
 
local con = net.open("192.168.1.100", 6667)
 
--FUNCTIONS
function sendString(s)
    con:write(s)
    print('Sending ' .. string.sub(s,1,s:len()-1) .. ' to server...')
    con:flush()
end
 
function reciveString()
    local s = con:read()
    print('Recived ' .. s .. ' from server...')
    con:flush()
end
 
--MAIN
 
if con then
    print('Connected to the server!')
end
 
while running do
    local s = term.read()
    sendString(s)
    reciveString()
    os.sleep(0)
end

And here the java code:

import java.io.*;
import java.net.*;

class TCPServer {
	public static void main(String argv[]) throws Exception

	{
		String clientSentence;
		String capitalizedSentence;
		ServerSocket welcomeSocket = new ServerSocket(6667);
		Socket connectionSocket = welcomeSocket.accept();

		while (true) {
			if (!connectionSocket.isConnected()) {
				connectionSocket = welcomeSocket.accept();
			} else {
				System.out.println("Connected to client");
				BufferedReader inFromClient = new BufferedReader(
						new InputStreamReader(connectionSocket.getInputStream()));
				clientSentence = inFromClient.readLine();
				System.out.println("Received: " + clientSentence);
				capitalizedSentence = clientSentence.toUpperCase() + "\n";
				DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
				System.out.println("Sending: " + capitalizedSentence);
				outToClient.writeBytes(capitalizedSentence);
			}

		}
	}
}

Also make sure you have TCPEnabled on the config file and if your tcp server is in the same machine as the minecraft serve remove form the ip blacklist your networks ip.

 

Hope this helps someone

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use and Privacy Policy.